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

4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
5 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
5 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
5 years ago
4 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
5 years ago
5 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
5 years ago
5 years ago
3 years ago
4 years ago
3 years ago
5 years ago
3 years ago
4 years ago
4 years ago
5 years ago
3 years ago
4 years ago
5 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
5 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314
  1. package repo
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "os"
  10. "regexp"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "unicode/utf8"
  16. "code.gitea.io/gitea/modules/grampus"
  17. "code.gitea.io/gitea/modules/timeutil"
  18. "github.com/unknwon/i18n"
  19. "code.gitea.io/gitea/models"
  20. "code.gitea.io/gitea/modules/auth"
  21. "code.gitea.io/gitea/modules/base"
  22. "code.gitea.io/gitea/modules/cloudbrain"
  23. "code.gitea.io/gitea/modules/context"
  24. "code.gitea.io/gitea/modules/git"
  25. "code.gitea.io/gitea/modules/log"
  26. "code.gitea.io/gitea/modules/modelarts"
  27. "code.gitea.io/gitea/modules/setting"
  28. "code.gitea.io/gitea/modules/storage"
  29. "code.gitea.io/gitea/modules/util"
  30. )
  31. const (
  32. tplCloudBrainNew base.TplName = "repo/cloudbrain/new"
  33. tplCloudBrainShow base.TplName = "repo/cloudbrain/show"
  34. tplCloudBrainShowModels base.TplName = "repo/cloudbrain/models/index"
  35. tplCloudBrainBenchmarkIndex base.TplName = "repo/cloudbrain/benchmark/index"
  36. tplCloudBrainBenchmarkNew base.TplName = "repo/cloudbrain/benchmark/new"
  37. tplCloudBrainBenchmarkShow base.TplName = "repo/cloudbrain/benchmark/show"
  38. tplCloudBrainImageSubmit base.TplName = "repo/cloudbrain/image/submit"
  39. tplCloudBrainImageEdit base.TplName = "repo/cloudbrain/image/edit"
  40. tplCloudBrainTrainJobNew base.TplName = "repo/cloudbrain/trainjob/new"
  41. tplCloudBrainTrainJobShow base.TplName = "repo/cloudbrain/trainjob/show"
  42. )
  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("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.JobWaiting) {
  495. duration = 0
  496. } else if task.Status == string(models.JobRunning) {
  497. duration = time.Now().Unix() - int64(task.CreatedUnix)
  498. } else {
  499. duration = int64(task.UpdatedUnix) - int64(task.CreatedUnix)
  500. }
  501. task.Duration = duration
  502. }
  503. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  504. }
  505. ctx.Data["duration"] = task.TrainJobDuration
  506. if len(task.Parameters) > 0 {
  507. var parameters models.Parameters
  508. err := json.Unmarshal([]byte(task.Parameters), &parameters)
  509. if err != nil {
  510. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  511. task.Parameters = ""
  512. } else {
  513. if len(parameters.Parameter) > 0 {
  514. paramTemp := ""
  515. for _, Parameter := range parameters.Parameter {
  516. param := Parameter.Label + " = " + Parameter.Value + "; "
  517. paramTemp = paramTemp + param
  518. }
  519. task.Parameters = paramTemp[:len(paramTemp)-2]
  520. } else {
  521. task.Parameters = ""
  522. }
  523. }
  524. }
  525. ctx.Data["task"] = task
  526. ctx.Data["jobName"] = task.JobName
  527. ctx.Data["displayJobName"] = task.DisplayJobName
  528. version_list_task := make([]*models.Cloudbrain, 0)
  529. version_list_task = append(version_list_task, task)
  530. ctx.Data["version_list_task"] = version_list_task
  531. ctx.Data["debugListType"] = debugListType
  532. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  533. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  534. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  535. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  536. ctx.Data["branchName"] = task.BranchName
  537. ctx.HTML(200, tpName)
  538. }
  539. func CloudBrainDebug(ctx *context.Context) {
  540. task := ctx.Cloudbrain
  541. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  542. ctx.Redirect(debugUrl)
  543. }
  544. func CloudBrainCommitImageShow(ctx *context.Context) {
  545. ctx.Data["PageIsCloudBrain"] = true
  546. ctx.Data["Type"] = ctx.Cloudbrain.Type
  547. ctx.HTML(200, tplCloudBrainImageSubmit)
  548. }
  549. func CloudBrainImageEdit(ctx *context.Context) {
  550. ctx.Data["PageIsImageEdit"] = true
  551. ctx.Data["PageFrom"] = ctx.Params(":from")
  552. var ID = ctx.Params(":id")
  553. id, err := strconv.ParseInt(ID, 10, 64)
  554. if err != nil {
  555. log.Error("GetImageByID failed:%v", err.Error())
  556. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  557. }
  558. image, err := models.GetImageByID(id)
  559. if err != nil {
  560. log.Error("GetImageByID failed:%v", err.Error())
  561. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  562. }
  563. ctx.Data["Image"] = image
  564. ctx.HTML(http.StatusOK, tplCloudBrainImageEdit)
  565. }
  566. func CloudBrainImageEditPost(ctx *context.Context, form auth.EditImageCloudBrainForm) {
  567. if utf8.RuneCountInString(form.Description) > 255 {
  568. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  569. return
  570. }
  571. validTopics, errMessage := checkTopics(form.Topics)
  572. if errMessage != "" {
  573. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  574. return
  575. }
  576. image, err := models.GetImageByID(form.ID)
  577. if err != nil {
  578. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  579. }
  580. image.IsPrivate = form.IsPrivate
  581. image.Description = form.Description
  582. err = models.WithTx(func(ctx models.DBContext) error {
  583. if err := models.UpdateLocalImage(image); err != nil {
  584. return err
  585. }
  586. if err := models.SaveImageTopics(image.ID, validTopics...); err != nil {
  587. return err
  588. }
  589. return nil
  590. })
  591. if err != nil {
  592. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  593. } else {
  594. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  595. }
  596. }
  597. func CloudBrainImageDelete(ctx *context.Context) {
  598. var ID = ctx.Params(":id")
  599. id, err := strconv.ParseInt(ID, 10, 64)
  600. if err != nil {
  601. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_not_exist")))
  602. return
  603. }
  604. err = models.DeleteLocalImage(id)
  605. if err != nil {
  606. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_delete_fail")))
  607. } else {
  608. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  609. }
  610. }
  611. func CloudBrainCommitImageCheck(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  612. isExist, _ := models.IsImageExistByUser(form.Tag, ctx.User.ID)
  613. if isExist {
  614. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("repo.image_overwrite")))
  615. } else {
  616. ctx.JSON(http.StatusOK, models.BaseOKMessage)
  617. }
  618. }
  619. func CloudBrainAdminCommitImage(ctx *context.Context, form auth.CommitAdminImageCloudBrainForm) {
  620. if !NamePattern.MatchString(form.Tag) {
  621. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  622. return
  623. }
  624. if utf8.RuneCountInString(form.Description) > 255 {
  625. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  626. return
  627. }
  628. validTopics, errMessage := checkTopics(form.Topics)
  629. if errMessage != "" {
  630. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  631. return
  632. }
  633. err := cloudbrain.CommitAdminImage(models.CommitImageParams{
  634. CommitImageCloudBrainParams: models.CommitImageCloudBrainParams{
  635. ImageDescription: form.Description,
  636. ImageTag: form.Tag,
  637. },
  638. IsPrivate: form.IsPrivate,
  639. CloudBrainType: form.Type,
  640. Topics: validTopics,
  641. UID: ctx.User.ID,
  642. Type: models.GetRecommondType(form.IsRecommend),
  643. Place: form.Place,
  644. })
  645. if err != nil {
  646. log.Error("CommitImagefailed")
  647. if models.IsErrImageTagExist(err) {
  648. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_exist")))
  649. } else if models.IsErrorImageCommitting(err) {
  650. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_committing")))
  651. } else {
  652. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_commit_fail")))
  653. }
  654. return
  655. }
  656. ctx.JSON(200, models.BaseOKMessage)
  657. }
  658. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  659. if !NamePattern.MatchString(form.Tag) {
  660. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.title_format_err")))
  661. return
  662. }
  663. if utf8.RuneCountInString(form.Description) > 255 {
  664. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr("dataset.description_format_err", 255)))
  665. return
  666. }
  667. validTopics, errMessage := checkTopics(form.Topics)
  668. if errMessage != "" {
  669. ctx.JSON(http.StatusOK, models.BaseErrorMessage(ctx.Tr(errMessage)))
  670. return
  671. }
  672. err := cloudbrain.CommitImage(ctx.Cloudbrain.JobID, models.CommitImageParams{
  673. CommitImageCloudBrainParams: models.CommitImageCloudBrainParams{
  674. Ip: ctx.Cloudbrain.ContainerIp,
  675. TaskContainerId: ctx.Cloudbrain.ContainerID,
  676. ImageDescription: form.Description,
  677. ImageTag: form.Tag,
  678. },
  679. IsPrivate: form.IsPrivate,
  680. CloudBrainType: form.Type,
  681. Topics: validTopics,
  682. UID: ctx.User.ID,
  683. })
  684. if err != nil {
  685. log.Error("CommitImage(%s) failed:%v", ctx.Cloudbrain.JobName, err.Error(), ctx.Data["msgID"])
  686. if models.IsErrImageTagExist(err) {
  687. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_exist")))
  688. } else if models.IsErrorImageCommitting(err) {
  689. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_committing")))
  690. } else {
  691. ctx.JSON(200, models.BaseErrorMessage(ctx.Tr("repo.image_commit_fail")))
  692. }
  693. return
  694. }
  695. ctx.JSON(200, models.BaseOKMessage)
  696. }
  697. func checkTopics(Topics string) ([]string, string) {
  698. var topics = make([]string, 0)
  699. var topicsStr = strings.TrimSpace(Topics)
  700. if len(topicsStr) > 0 {
  701. topics = strings.Split(topicsStr, ",")
  702. }
  703. validTopics, invalidTopics := models.SanitizeAndValidateImageTopics(topics)
  704. if len(validTopics) > 25 {
  705. return nil, "repo.topic.count_prompt"
  706. }
  707. if len(invalidTopics) > 0 {
  708. return nil, "repo.imagetopic.format_prompt"
  709. }
  710. return validTopics, ""
  711. }
  712. func CloudBrainStop(ctx *context.Context) {
  713. var ID = ctx.Params(":id")
  714. var resultCode = "0"
  715. var errorMsg = ""
  716. var status = ""
  717. task := ctx.Cloudbrain
  718. for {
  719. if task.Status == string(models.JobStopped) || task.Status == string(models.JobFailed) || task.Status == string(models.JobSucceeded) {
  720. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  721. resultCode = "-1"
  722. errorMsg = "system error"
  723. break
  724. }
  725. err := cloudbrain.StopJob(task.JobID)
  726. if err != nil {
  727. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  728. resultCode = "-1"
  729. errorMsg = "system error"
  730. break
  731. }
  732. task.Status = string(models.JobStopped)
  733. if task.EndTime == 0 {
  734. task.EndTime = timeutil.TimeStampNow()
  735. }
  736. task.ComputeAndSetDuration()
  737. err = models.UpdateJob(task)
  738. if err != nil {
  739. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  740. resultCode = "-1"
  741. errorMsg = "system error"
  742. break
  743. }
  744. status = task.Status
  745. break
  746. }
  747. ctx.JSON(200, map[string]interface{}{
  748. "result_code": resultCode,
  749. "error_msg": errorMsg,
  750. "status": status,
  751. "id": ID,
  752. "StatusOK": 0,
  753. })
  754. }
  755. func StopJobsByUserID(userID int64) {
  756. cloudBrains, err := models.GetCloudbrainsNeededStopByUserID(userID)
  757. if err != nil {
  758. log.Warn("Failed to get cloudBrain info", err)
  759. return
  760. }
  761. StopJobs(cloudBrains)
  762. }
  763. func StopJobsByRepoID(repoID int64) {
  764. cloudBrains, err := models.GetCloudbrainsNeededStopByRepoID(repoID)
  765. if err != nil {
  766. log.Warn("Failed to get cloudBrain info", err)
  767. return
  768. }
  769. StopJobs(cloudBrains)
  770. }
  771. /**
  772. */
  773. func StopJobs(cloudBrains []*models.Cloudbrain) {
  774. for _, taskInfo := range cloudBrains {
  775. if taskInfo.Type == models.TypeCloudBrainOne {
  776. err := retry(3, time.Second*30, func() error {
  777. return cloudbrain.StopJob(taskInfo.JobID)
  778. })
  779. logErrorAndUpdateJobStatus(err, taskInfo)
  780. } else {
  781. if taskInfo.JobType == string(models.JobTypeTrain) {
  782. err := retry(3, time.Second*30, func() error {
  783. _, err := modelarts.StopTrainJob(taskInfo.JobID, strconv.FormatInt(taskInfo.VersionID, 10))
  784. return err
  785. })
  786. logErrorAndUpdateJobStatus(err, taskInfo)
  787. } else {
  788. param := models.NotebookAction{
  789. Action: models.ActionStop,
  790. }
  791. err := retry(3, time.Second*30, func() error {
  792. _, err := modelarts.ManageNotebook(taskInfo.JobID, param)
  793. return err
  794. })
  795. logErrorAndUpdateJobStatus(err, taskInfo)
  796. }
  797. }
  798. }
  799. }
  800. func retry(attempts int, sleep time.Duration, f func() error) (err error) {
  801. for i := 0; i < attempts; i++ {
  802. if i > 0 {
  803. log.Warn("retrying after error:", err)
  804. time.Sleep(sleep)
  805. }
  806. err = f()
  807. if err == nil {
  808. return nil
  809. }
  810. }
  811. return fmt.Errorf("after %d attempts, last error: %s", attempts, err)
  812. }
  813. func logErrorAndUpdateJobStatus(err error, taskInfo *models.Cloudbrain) {
  814. if err != nil {
  815. log.Warn("Failed to stop cloudBrain job:"+taskInfo.JobID, err)
  816. } else {
  817. taskInfo.Status = string(models.JobStopped)
  818. if taskInfo.EndTime == 0 {
  819. taskInfo.EndTime = timeutil.TimeStampNow()
  820. }
  821. taskInfo.ComputeAndSetDuration()
  822. err = models.UpdateJob(taskInfo)
  823. if err != nil {
  824. log.Warn("UpdateJob failed", err)
  825. }
  826. }
  827. }
  828. func CloudBrainDel(ctx *context.Context) {
  829. var listType = ctx.Query("debugListType")
  830. if err := deleteCloudbrainJob(ctx); err != nil {
  831. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  832. ctx.ServerError(err.Error(), err)
  833. return
  834. }
  835. var isAdminPage = ctx.Query("isadminpage")
  836. var isHomePage = ctx.Query("ishomepage")
  837. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  838. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  839. } else if isHomePage == "true" {
  840. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  841. } else {
  842. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/debugjob?debugListType=" + listType)
  843. }
  844. }
  845. func deleteCloudbrainJob(ctx *context.Context) error {
  846. task := ctx.Cloudbrain
  847. if task.Status != string(models.JobStopped) && task.Status != string(models.JobFailed) && task.Status != string(models.JobSucceeded) {
  848. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  849. return errors.New("the job has not been stopped")
  850. }
  851. err := models.DeleteJob(task)
  852. if err != nil {
  853. log.Error("DeleteJob failed: %v", err, ctx.Data["msgID"])
  854. return err
  855. }
  856. deleteJobStorage(task.JobName, models.TypeCloudBrainOne)
  857. return nil
  858. }
  859. func CloudBrainShowModels(ctx *context.Context) {
  860. ctx.Data["PageIsCloudBrain"] = true
  861. ID := ctx.Params(":id")
  862. parentDir := ctx.Query("parentDir")
  863. dirArray := strings.Split(parentDir, "/")
  864. task, err := models.GetCloudbrainByID(ID)
  865. if err != nil {
  866. log.Error("no such job!", ctx.Data["msgID"])
  867. ctx.ServerError("no such job:", err)
  868. return
  869. }
  870. //get dirs
  871. dirs, err := GetModelDirs(task.JobName, parentDir)
  872. if err != nil {
  873. log.Error("GetModelDirs failed:%v", err.Error(), ctx.Data["msgID"])
  874. ctx.ServerError("GetModelDirs failed:", err)
  875. return
  876. }
  877. var fileInfos []storage.FileInfo
  878. err = json.Unmarshal([]byte(dirs), &fileInfos)
  879. if err != nil {
  880. log.Error("json.Unmarshal failed:%v", err.Error(), ctx.Data["msgID"])
  881. ctx.ServerError("json.Unmarshal failed:", err)
  882. return
  883. }
  884. for i, fileInfo := range fileInfos {
  885. temp, _ := time.Parse("2006-01-02 15:04:05", fileInfo.ModTime)
  886. fileInfos[i].ModTime = temp.Local().Format("2006-01-02 15:04:05")
  887. }
  888. sort.Slice(fileInfos, func(i, j int) bool {
  889. return fileInfos[i].ModTime > fileInfos[j].ModTime
  890. })
  891. ctx.Data["Path"] = dirArray
  892. ctx.Data["Dirs"] = fileInfos
  893. ctx.Data["task"] = task
  894. ctx.Data["ID"] = ID
  895. ctx.HTML(200, tplCloudBrainShowModels)
  896. }
  897. func GetPublicImages(ctx *context.Context) {
  898. uid := getUID(ctx)
  899. opts := models.SearchImageOptions{
  900. IncludePublicOnly: true,
  901. UID: uid,
  902. Keyword: ctx.Query("q"),
  903. Topics: ctx.Query("topic"),
  904. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  905. SearchOrderBy: "type desc, num_stars desc,id desc",
  906. Status: models.IMAGE_STATUS_SUCCESS,
  907. CloudbrainType: ctx.QueryInt("cloudbrainType"),
  908. }
  909. getImages(ctx, &opts)
  910. }
  911. func GetCustomImages(ctx *context.Context) {
  912. uid := getUID(ctx)
  913. opts := models.SearchImageOptions{
  914. UID: uid,
  915. IncludeOwnerOnly: true,
  916. Keyword: ctx.Query("q"),
  917. Topics: ctx.Query("topic"),
  918. Status: -1,
  919. SearchOrderBy: "id desc",
  920. }
  921. getImages(ctx, &opts)
  922. }
  923. func GetStarImages(ctx *context.Context) {
  924. uid := getUID(ctx)
  925. opts := models.SearchImageOptions{
  926. UID: uid,
  927. IncludeStarByMe: true,
  928. Keyword: ctx.Query("q"),
  929. Topics: ctx.Query("topic"),
  930. Status: models.IMAGE_STATUS_SUCCESS,
  931. SearchOrderBy: "id desc",
  932. }
  933. getImages(ctx, &opts)
  934. }
  935. func getUID(ctx *context.Context) int64 {
  936. var uid int64 = -1
  937. if ctx.IsSigned {
  938. uid = ctx.User.ID
  939. }
  940. return uid
  941. }
  942. func GetAllImages(ctx *context.Context) {
  943. uid := getUID(ctx)
  944. opts := models.SearchImageOptions{
  945. UID: uid,
  946. Keyword: ctx.Query("q"),
  947. Topics: ctx.Query("topic"),
  948. IncludeOfficialOnly: ctx.QueryBool("recommend"),
  949. SearchOrderBy: "id desc",
  950. Status: -1,
  951. }
  952. if ctx.Query("private") != "" {
  953. if ctx.QueryBool("private") {
  954. opts.IncludePrivateOnly = true
  955. } else {
  956. opts.IncludePublicOnly = true
  957. }
  958. }
  959. getImages(ctx, &opts)
  960. }
  961. func getImages(ctx *context.Context, opts *models.SearchImageOptions) {
  962. page := ctx.QueryInt("page")
  963. if page <= 0 {
  964. page = 1
  965. }
  966. pageSize := ctx.QueryInt("pageSize")
  967. if pageSize <= 0 {
  968. pageSize = 15
  969. }
  970. opts.ListOptions = models.ListOptions{
  971. Page: page,
  972. PageSize: pageSize,
  973. }
  974. imageList, total, err := models.SearchImage(opts)
  975. if err != nil {
  976. log.Error("Can not get images:%v", err)
  977. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  978. Count: 0,
  979. Images: []*models.Image{},
  980. })
  981. } else {
  982. ctx.JSON(http.StatusOK, models.ImagesPageResult{
  983. Count: total,
  984. Images: imageList,
  985. })
  986. }
  987. }
  988. func GetModelDirs(jobName string, parentDir string) (string, error) {
  989. var req string
  990. modelActualPath := storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/")
  991. if parentDir == "" {
  992. req = "baseDir=" + modelActualPath
  993. } else {
  994. req = "baseDir=" + modelActualPath + "&parentDir=" + parentDir
  995. }
  996. return getDirs(req)
  997. }
  998. func CloudBrainDownloadModel(ctx *context.Context) {
  999. parentDir := ctx.Query("parentDir")
  1000. fileName := ctx.Query("fileName")
  1001. jobName := ctx.Query("jobName")
  1002. filePath := "jobs/" + jobName + "/model/" + parentDir
  1003. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  1004. if err != nil {
  1005. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  1006. ctx.ServerError("PresignedGetURL", err)
  1007. return
  1008. }
  1009. ctx.Resp.Header().Set("Cache-Control", "max-age=0")
  1010. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  1011. }
  1012. func GetRate(ctx *context.Context) {
  1013. isObjectDetcionAll := ctx.QueryBool("isObjectDetcionAll")
  1014. if isObjectDetcionAll {
  1015. ctx.Redirect(setting.BenchmarkServerHost + "?username=admin")
  1016. return
  1017. }
  1018. var ID = ctx.Params(":id")
  1019. job, err := models.GetCloudbrainByID(ID)
  1020. if err != nil {
  1021. ctx.ServerError("GetCloudbrainByJobID failed", err)
  1022. return
  1023. }
  1024. if job.JobType == string(models.JobTypeBenchmark) {
  1025. log.Info("url=" + setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1026. ctx.Redirect(setting.BenchmarkServerHost + "?username=" + ctx.User.Name)
  1027. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  1028. ctx.Redirect(setting.Snn4imagenetServerHost)
  1029. } else if job.JobType == string(models.JobTypeBrainScore) {
  1030. ctx.Redirect(setting.BrainScoreServerHost)
  1031. } else {
  1032. log.Error("JobType error:%s", job.JobType, ctx.Data["msgID"])
  1033. }
  1034. }
  1035. func downloadCode(repo *models.Repository, codePath, branchName string) error {
  1036. //add "file:///" prefix to make the depth valid
  1037. if err := git.Clone(CLONE_FILE_PREFIX+repo.RepoPath(), codePath, git.CloneRepoOptions{Branch: branchName, Depth: 1}); err != nil {
  1038. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  1039. return err
  1040. }
  1041. configFile, err := os.OpenFile(codePath+"/.git/config", os.O_RDWR, 0666)
  1042. if err != nil {
  1043. log.Error("open file(%s) failed:%v", codePath+"/,git/config", err)
  1044. return err
  1045. }
  1046. defer configFile.Close()
  1047. pos := int64(0)
  1048. reader := bufio.NewReader(configFile)
  1049. for {
  1050. line, err := reader.ReadString('\n')
  1051. if err != nil {
  1052. if err == io.EOF {
  1053. log.Error("not find the remote-url")
  1054. return nil
  1055. } else {
  1056. log.Error("read error: %v", err)
  1057. return err
  1058. }
  1059. }
  1060. if strings.Contains(line, "url") && strings.Contains(line, ".git") {
  1061. originUrl := "\turl = " + repo.CloneLink().HTTPS + "\n"
  1062. if len(line) > len(originUrl) {
  1063. originUrl += strings.Repeat(" ", len(line)-len(originUrl))
  1064. }
  1065. bytes := []byte(originUrl)
  1066. _, err := configFile.WriteAt(bytes, pos)
  1067. if err != nil {
  1068. log.Error("WriteAt failed:%v", err)
  1069. return err
  1070. }
  1071. break
  1072. }
  1073. pos += int64(len(line))
  1074. }
  1075. return nil
  1076. }
  1077. func downloadRateCode(repo *models.Repository, taskName, rateOwnerName, rateRepoName, codePath, benchmarkCategory, gpuType, userName string) error {
  1078. err := os.MkdirAll(codePath, os.ModePerm)
  1079. if err != nil {
  1080. log.Error("mkdir codePath failed", err.Error())
  1081. return err
  1082. }
  1083. repoExt, err := models.GetRepositoryByOwnerAndName(rateOwnerName, rateRepoName)
  1084. if err != nil {
  1085. log.Error("GetRepositoryByOwnerAndName(%s) failed", rateRepoName, err.Error())
  1086. return err
  1087. }
  1088. if err := git.Clone(CLONE_FILE_PREFIX+repoExt.RepoPath(), codePath, git.CloneRepoOptions{Depth: 1}); err != nil {
  1089. log.Error("Failed to clone repository: %s (%v)", repoExt.FullName(), err)
  1090. return err
  1091. }
  1092. fileName := codePath + cloudbrain.TaskInfoName
  1093. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1094. if err != nil {
  1095. log.Error("OpenFile failed", err.Error())
  1096. return err
  1097. }
  1098. defer f.Close()
  1099. data, err := json.Marshal(models.TaskInfo{
  1100. Username: userName,
  1101. TaskName: taskName,
  1102. CodeName: repo.Name,
  1103. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  1104. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  1105. GpuType: gpuType,
  1106. })
  1107. if err != nil {
  1108. log.Error("json.Marshal failed", err.Error())
  1109. return err
  1110. }
  1111. _, err = f.Write(data)
  1112. if err != nil {
  1113. log.Error("WriteString failed", err.Error())
  1114. return err
  1115. }
  1116. return nil
  1117. }
  1118. func uploadCodeToMinio(codePath, jobName, parentDir string) error {
  1119. files, err := readDir(codePath)
  1120. if err != nil {
  1121. log.Error("readDir(%s) failed: %s", codePath, err.Error())
  1122. return err
  1123. }
  1124. for _, file := range files {
  1125. if file.IsDir() {
  1126. if err = uploadCodeToMinio(codePath+file.Name()+"/", jobName, parentDir+file.Name()+"/"); err != nil {
  1127. log.Error("uploadCodeToMinio(%s) failed: %s", file.Name(), err.Error())
  1128. return err
  1129. }
  1130. } else {
  1131. destObject := setting.CBCodePathPrefix + jobName + parentDir + file.Name()
  1132. sourceFile := codePath + file.Name()
  1133. err = storage.Attachments.UploadObject(destObject, sourceFile)
  1134. if err != nil {
  1135. log.Error("UploadObject(%s) failed: %s", file.Name(), err.Error())
  1136. return err
  1137. }
  1138. }
  1139. }
  1140. return nil
  1141. }
  1142. func mkModelPath(modelPath string) error {
  1143. err := os.MkdirAll(modelPath, os.ModePerm)
  1144. if err != nil {
  1145. log.Error("MkdirAll(%s) failed:%v", modelPath, err)
  1146. return err
  1147. }
  1148. fileName := modelPath + "README"
  1149. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  1150. if err != nil {
  1151. log.Error("OpenFile failed", err.Error())
  1152. return err
  1153. }
  1154. defer f.Close()
  1155. _, err = f.WriteString("You can put the model file into this directory and download it by the web page.")
  1156. if err != nil {
  1157. log.Error("WriteString failed", err.Error())
  1158. return err
  1159. }
  1160. return nil
  1161. }
  1162. func deleteJobStorage(jobName string, cloudbrainType int) error {
  1163. //delete local
  1164. localJobPath := setting.JobPath + jobName
  1165. err := os.RemoveAll(localJobPath)
  1166. if err != nil {
  1167. log.Error("RemoveAll(%s) failed:%v", localJobPath, err)
  1168. }
  1169. //delete oss
  1170. if cloudbrainType == models.TypeCloudBrainOne {
  1171. dirPath := setting.CBCodePathPrefix + jobName + "/"
  1172. err = storage.Attachments.DeleteDir(dirPath)
  1173. if err != nil {
  1174. log.Error("DeleteDir(%s) failed:%v", localJobPath, err)
  1175. }
  1176. } else if cloudbrainType == models.TypeCloudBrainTwo {
  1177. //dirPath := setting.CodePathPrefix + jobName + "/"
  1178. //err = storage.ObsRemoveObject(setting.Bucket, dirPath)
  1179. //if err != nil {
  1180. // log.Error("ObsRemoveObject(%s) failed:%v", localJobPath, err)
  1181. //}
  1182. log.Info("no need to delete")
  1183. } else {
  1184. log.Error("cloudbrainType(%d) error", cloudbrainType)
  1185. }
  1186. return nil
  1187. }
  1188. func SyncCloudbrainStatus() {
  1189. cloudBrains, err := models.GetCloudBrainUnStoppedJob()
  1190. if err != nil {
  1191. log.Error("GetCloudBrainUnStoppedJob failed:", err.Error())
  1192. return
  1193. }
  1194. for _, task := range cloudBrains {
  1195. if task.Type == models.TypeCloudBrainOne {
  1196. result, err := cloudbrain.GetJob(task.JobID)
  1197. if err != nil {
  1198. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1199. continue
  1200. }
  1201. if result != nil {
  1202. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  1203. taskRoles := jobRes.TaskRoles
  1204. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1205. task.Status = taskRes.TaskStatuses[0].State
  1206. if task.Status != string(models.JobWaiting) {
  1207. models.ParseAndSetDurationFromCloudBrainOne(jobRes, task)
  1208. err = models.UpdateJob(task)
  1209. if err != nil {
  1210. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1211. }
  1212. var maxDuration int64
  1213. if task.JobType == string(models.JobTypeBenchmark) {
  1214. maxDuration = setting.BenchmarkMaxDuration
  1215. } else if task.JobType == string(models.JobTypeSnn4imagenet) || task.JobType == string(models.JobTypeBrainScore) {
  1216. maxDuration = setting.ModelBenchmarkMaxDuration
  1217. } else {
  1218. maxDuration = setting.MaxDuration
  1219. }
  1220. if task.Duration >= maxDuration && task.JobType != string(models.JobTypeTrain) {
  1221. log.Info("begin to stop job(%s), because of the duration", task.DisplayJobName)
  1222. err = cloudbrain.StopJob(task.JobID)
  1223. if err != nil {
  1224. log.Error("StopJob(%s) failed:%v", task.DisplayJobName, err)
  1225. continue
  1226. }
  1227. task.Status = string(models.JobStopped)
  1228. if task.EndTime == 0 {
  1229. task.EndTime = timeutil.TimeStampNow()
  1230. }
  1231. task.ComputeAndSetDuration()
  1232. err = models.UpdateJob(task)
  1233. if err != nil {
  1234. log.Error("UpdateJob(%s) failed:%v", task.DisplayJobName, err)
  1235. continue
  1236. }
  1237. }
  1238. }
  1239. }
  1240. } else if task.Type == models.TypeCloudBrainTwo {
  1241. if task.JobType == string(models.JobTypeDebug) {
  1242. //result, err := modelarts.GetJob(task.JobID)
  1243. result, err := modelarts.GetNotebook2(task.JobID)
  1244. if err != nil {
  1245. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1246. continue
  1247. }
  1248. if result != nil {
  1249. task.Status = result.Status
  1250. if task.StartTime == 0 && result.Lease.UpdateTime > 0 {
  1251. task.StartTime = timeutil.TimeStamp(result.Lease.UpdateTime / 1000)
  1252. }
  1253. if task.EndTime == 0 && models.IsModelArtsDebugJobTerminal(task.Status) {
  1254. task.EndTime = timeutil.TimeStampNow()
  1255. }
  1256. task.CorrectCreateUnix()
  1257. task.ComputeAndSetDuration()
  1258. err = models.UpdateJob(task)
  1259. if err != nil {
  1260. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1261. continue
  1262. }
  1263. }
  1264. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1265. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1266. if err != nil {
  1267. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1268. continue
  1269. }
  1270. if result != nil {
  1271. task.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  1272. task.Duration = result.Duration / 1000
  1273. task.TrainJobDuration = result.TrainJobDuration
  1274. if task.StartTime == 0 && result.StartTime > 0 {
  1275. task.StartTime = timeutil.TimeStamp(result.StartTime / 1000)
  1276. }
  1277. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1278. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  1279. task.EndTime = task.StartTime.Add(task.Duration)
  1280. }
  1281. task.CorrectCreateUnix()
  1282. err = models.UpdateJob(task)
  1283. if err != nil {
  1284. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1285. continue
  1286. }
  1287. }
  1288. } else {
  1289. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1290. }
  1291. } else if task.Type == models.TypeC2Net {
  1292. result, err := grampus.GetJob(task.JobID)
  1293. if err != nil {
  1294. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1295. continue
  1296. }
  1297. if result != nil {
  1298. if len(result.JobInfo.Tasks[0].CenterID) == 1 && len(result.JobInfo.Tasks[0].CenterName) == 1 {
  1299. task.AiCenter = result.JobInfo.Tasks[0].CenterID[0] + "+" + result.JobInfo.Tasks[0].CenterName[0]
  1300. }
  1301. task.Status = grampus.TransTrainJobStatus(result.JobInfo.Status)
  1302. task.Duration = result.JobInfo.RunSec
  1303. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1304. if task.StartTime == 0 && result.JobInfo.StartedAt > 0 {
  1305. task.StartTime = timeutil.TimeStamp(result.JobInfo.StartedAt)
  1306. }
  1307. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  1308. task.EndTime = task.StartTime.Add(task.Duration)
  1309. }
  1310. task.CorrectCreateUnix()
  1311. err = models.UpdateJob(task)
  1312. if err != nil {
  1313. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1314. continue
  1315. }
  1316. }
  1317. } else {
  1318. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1319. }
  1320. }
  1321. return
  1322. }
  1323. func HandleTaskWithNoDuration(ctx *context.Context) {
  1324. mode := ctx.Query("mode")
  1325. log.Info("HandleTaskWithNoDuration start")
  1326. count := 0
  1327. start := time.Now().Unix()
  1328. for {
  1329. var cloudBrains []*models.Cloudbrain
  1330. var err error
  1331. if mode == "1" {
  1332. cloudBrains, err = models.GetStoppedJobWithNoStartTimeEndTime()
  1333. } else {
  1334. cloudBrains, err = models.GetStoppedJobWithNoDurationJob()
  1335. }
  1336. if err != nil {
  1337. log.Error("HandleTaskWithNoTrainJobDuration failed:", err.Error())
  1338. break
  1339. }
  1340. if len(cloudBrains) == 0 {
  1341. log.Info("HandleTaskWithNoTrainJobDuration:no task need handle")
  1342. break
  1343. }
  1344. handleNoDurationTask(cloudBrains)
  1345. count += len(cloudBrains)
  1346. if len(cloudBrains) < 100 {
  1347. log.Info("HandleTaskWithNoTrainJobDuration:task less than 100")
  1348. break
  1349. }
  1350. if time.Now().Unix()-start > 600 {
  1351. log.Info("HandleTaskWithNoDuration : time out")
  1352. ctx.JSON(200, fmt.Sprintf("task stop for time out,count=%d", count))
  1353. return
  1354. }
  1355. }
  1356. log.Info("HandleTaskWithNoTrainJobDuration:count=%d", count)
  1357. ctx.JSON(200, fmt.Sprintf("success,count=%d", count))
  1358. }
  1359. func handleNoDurationTask(cloudBrains []*models.Cloudbrain) {
  1360. for _, task := range cloudBrains {
  1361. time.Sleep(time.Millisecond * 100)
  1362. log.Info("Handle job ,%+v", task)
  1363. if task.Type == models.TypeCloudBrainOne {
  1364. result, err := cloudbrain.GetJob(task.JobID)
  1365. if err != nil {
  1366. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1367. updateDefaultDuration(task)
  1368. continue
  1369. }
  1370. if result != nil {
  1371. if result.Msg != "success" {
  1372. updateDefaultDuration(task)
  1373. continue
  1374. }
  1375. jobRes, err := models.ConvertToJobResultPayload(result.Payload)
  1376. if err != nil || len(jobRes.TaskRoles) == 0 {
  1377. updateDefaultDuration(task)
  1378. continue
  1379. }
  1380. taskRoles := jobRes.TaskRoles
  1381. taskRes, err := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  1382. if err != nil || len(taskRes.TaskStatuses) == 0 {
  1383. updateDefaultDuration(task)
  1384. continue
  1385. }
  1386. task.Status = taskRes.TaskStatuses[0].State
  1387. log.Info("task startTime = %v endTime= %v ,jobId=%d", jobRes.JobStatus.StartTime, jobRes.JobStatus.EndTime, task.ID)
  1388. if jobRes.JobStatus.CreatedTime > 0 {
  1389. task.StartTime = timeutil.TimeStamp(jobRes.JobStatus.CreatedTime / 1000)
  1390. if jobRes.JobStatus.CompletedTime > 0 {
  1391. task.EndTime = timeutil.TimeStamp(jobRes.JobStatus.CompletedTime / 1000)
  1392. } else {
  1393. task.EndTime = task.UpdatedUnix
  1394. }
  1395. } else {
  1396. task.StartTime = 0
  1397. task.EndTime = 0
  1398. }
  1399. if task.EndTime < task.StartTime {
  1400. log.Info("endTime[%v] is less than starTime[%v],jobId=%d", task.EndTime, task.StartTime, task.ID)
  1401. st := task.StartTime
  1402. task.StartTime = task.EndTime
  1403. task.EndTime = st
  1404. }
  1405. task.Duration = task.EndTime.AsTime().Unix() - task.StartTime.AsTime().Unix()
  1406. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  1407. err = models.UpdateJobDurationWithDeleted(task)
  1408. if err != nil {
  1409. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1410. }
  1411. }
  1412. } else if task.Type == models.TypeCloudBrainTwo {
  1413. if task.JobType == string(models.JobTypeDebug) {
  1414. //result, err := modelarts.GetJob(task.JobID)
  1415. result, err := modelarts.GetNotebook2(task.JobID)
  1416. if err != nil {
  1417. log.Error("GetJob(%s) failed:%v", task.JobName, err)
  1418. updateDefaultDuration(task)
  1419. continue
  1420. }
  1421. if result != nil {
  1422. task.Status = result.Status
  1423. startTime := result.Lease.CreateTime
  1424. duration := result.Lease.Duration / 1000
  1425. if startTime > 0 {
  1426. task.StartTime = timeutil.TimeStamp(startTime / 1000)
  1427. task.EndTime = task.StartTime.Add(duration)
  1428. }
  1429. task.CorrectCreateUnix()
  1430. task.ComputeAndSetDuration()
  1431. err = models.UpdateJobDurationWithDeleted(task)
  1432. if err != nil {
  1433. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1434. continue
  1435. }
  1436. }
  1437. } else if task.JobType == string(models.JobTypeTrain) || task.JobType == string(models.JobTypeInference) {
  1438. result, err := modelarts.GetTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  1439. if err != nil {
  1440. log.Error("GetTrainJob(%s) failed:%v", task.JobName, err)
  1441. updateDefaultDuration(task)
  1442. continue
  1443. }
  1444. if result != nil {
  1445. startTime := result.StartTime / 1000
  1446. if startTime > 0 {
  1447. task.StartTime = timeutil.TimeStamp(startTime)
  1448. task.EndTime = task.StartTime.Add(result.Duration / 1000)
  1449. }
  1450. task.ComputeAndSetDuration()
  1451. err = models.UpdateJobDurationWithDeleted(task)
  1452. if err != nil {
  1453. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1454. continue
  1455. }
  1456. }
  1457. } else {
  1458. log.Error("task.JobType(%s) is error:%s", task.JobName, task.JobType)
  1459. }
  1460. } else {
  1461. log.Error("task.Type(%s) is error:%d", task.JobName, task.Type)
  1462. }
  1463. }
  1464. }
  1465. func updateDefaultDuration(task *models.Cloudbrain) {
  1466. log.Info("updateDefaultDuration: taskId=%d", task.ID)
  1467. task.StartTime = task.CreatedUnix
  1468. task.EndTime = task.UpdatedUnix
  1469. task.ComputeAndSetDuration()
  1470. err := models.UpdateJobDurationWithDeleted(task)
  1471. if err != nil {
  1472. log.Error("UpdateJob(%s) failed:%v", task.JobName, err)
  1473. }
  1474. }
  1475. func CloudBrainBenchmarkIndex(ctx *context.Context) {
  1476. MustEnableCloudbrain(ctx)
  1477. repo := ctx.Repo.Repository
  1478. page := ctx.QueryInt("page")
  1479. if page <= 0 {
  1480. page = 1
  1481. }
  1482. var jobTypes []string
  1483. jobTypes = append(jobTypes, string(models.JobTypeBenchmark), string(models.JobTypeBrainScore), string(models.JobTypeSnn4imagenet))
  1484. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  1485. ListOptions: models.ListOptions{
  1486. Page: page,
  1487. PageSize: setting.UI.IssuePagingNum,
  1488. },
  1489. RepoID: repo.ID,
  1490. Type: models.TypeCloudBrainOne,
  1491. JobTypes: jobTypes,
  1492. })
  1493. if err != nil {
  1494. ctx.ServerError("Get debugjob faild:", err)
  1495. return
  1496. }
  1497. for i, task := range ciTasks {
  1498. ciTasks[i].CanDel = cloudbrain.CanDeleteJob(ctx, &task.Cloudbrain)
  1499. ciTasks[i].Cloudbrain.ComputeResource = task.ComputeResource
  1500. if ciTasks[i].TrainJobDuration == "" {
  1501. if ciTasks[i].Duration == 0 {
  1502. var duration int64
  1503. if task.Status == string(models.JobRunning) {
  1504. duration = time.Now().Unix() - int64(task.Cloudbrain.CreatedUnix)
  1505. } else {
  1506. duration = int64(task.Cloudbrain.UpdatedUnix) - int64(task.Cloudbrain.CreatedUnix)
  1507. }
  1508. ciTasks[i].Duration = duration
  1509. }
  1510. ciTasks[i].TrainJobDuration = models.ConvertDurationToStr(ciTasks[i].Duration)
  1511. }
  1512. ciTasks[i].BenchmarkTypeName = ""
  1513. if ciTasks[i].JobType == string(models.JobTypeBenchmark) {
  1514. ciTasks[i].BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.algorithm")
  1515. } else if ciTasks[i].JobType == string(models.JobTypeSnn4imagenet) || ciTasks[i].JobType == string(models.JobTypeBrainScore) {
  1516. ciTasks[i].BenchmarkType = ctx.Tr("repo.cloudbrain.benchmark.model")
  1517. ciTasks[i].BenchmarkTypeName = ciTasks[i].JobType
  1518. if ciTasks[i].JobType == string(models.JobTypeSnn4imagenet) {
  1519. ciTasks[i].BenchmarkTypeRankLink = setting.Snn4imagenetServerHost
  1520. } else {
  1521. ciTasks[i].BenchmarkTypeRankLink = setting.BrainScoreServerHost
  1522. }
  1523. }
  1524. if task.BenchmarkTypeID > 0 {
  1525. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1526. if task.BenchmarkTypeID == benchmarkType.Id {
  1527. ciTasks[i].BenchmarkTypeRankLink = benchmarkType.RankLink
  1528. ciTasks[i].BenchmarkTypeName = benchmarkType.First
  1529. break
  1530. }
  1531. }
  1532. }
  1533. }
  1534. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  1535. ctx.Data["Page"] = pager
  1536. ctx.Data["PageIsCloudBrain"] = true
  1537. ctx.Data["Tasks"] = ciTasks
  1538. ctx.Data["CanCreate"] = cloudbrain.CanCreateOrDebugJob(ctx)
  1539. ctx.Data["RepoIsEmpty"] = repo.IsEmpty
  1540. ctx.HTML(200, tplCloudBrainBenchmarkIndex)
  1541. }
  1542. func GetChildTypes(ctx *context.Context) {
  1543. benchmarkTypeID := ctx.QueryInt("benchmark_type_id")
  1544. re := make(map[string]interface{})
  1545. for {
  1546. var isExist bool
  1547. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1548. if benchmarkTypeID == benchmarkType.Id {
  1549. isExist = true
  1550. re["child_types"] = benchmarkType.Second
  1551. re["result_code"] = "0"
  1552. break
  1553. }
  1554. }
  1555. if !isExist {
  1556. re["result_code"] = "1"
  1557. log.Error("no such benchmark_type_id", ctx.Data["MsgID"])
  1558. re["errMsg"] = "system error"
  1559. break
  1560. }
  1561. break
  1562. }
  1563. ctx.JSON(200, re)
  1564. }
  1565. func CloudBrainBenchmarkNew(ctx *context.Context) {
  1566. ctx.Data["description"] = ""
  1567. ctx.Data["benchmarkTypeID"] = -1
  1568. ctx.Data["benchmark_child_types_id_hidden"] = -1
  1569. err := cloudBrainNewDataPrepare(ctx)
  1570. if err != nil {
  1571. ctx.ServerError("get new cloudbrain info failed", err)
  1572. return
  1573. }
  1574. ctx.HTML(200, tplCloudBrainBenchmarkNew)
  1575. }
  1576. func getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID int, ctx *context.Context) (*models.BenchmarkDataset, error) {
  1577. var childInfo *models.BenchmarkDataset
  1578. var isExist bool
  1579. for _, benchmarkType := range GetBenchmarkTypes(ctx).BenchmarkType {
  1580. if benchmarkType.Id == benchmarkTypeID {
  1581. for _, childType := range benchmarkType.Second {
  1582. if childType.Id == benchmarkChildTypeID {
  1583. childInfo = childType
  1584. isExist = true
  1585. break
  1586. }
  1587. }
  1588. break
  1589. }
  1590. }
  1591. if !isExist {
  1592. log.Error("no such benchmark_type_id&benchmark_child_type_id")
  1593. return childInfo, errors.New("no such benchmark_type_id&benchmark_child_type_id")
  1594. }
  1595. return childInfo, nil
  1596. }
  1597. func getBenchmarkGpuQueue(gpuQueue string) (string, error) {
  1598. queue := ""
  1599. if benchmarkGpuInfos == nil {
  1600. if err := json.Unmarshal([]byte(setting.BenchmarkGpuTypes), &benchmarkGpuInfos); err != nil {
  1601. log.Error("json.Unmarshal BenchmarkGpuTypes(%s) failed:%v", setting.BenchmarkGpuTypes, err)
  1602. return queue, err
  1603. }
  1604. }
  1605. var isExist bool
  1606. for _, gpuInfo := range benchmarkGpuInfos.GpuInfo {
  1607. if gpuQueue == gpuInfo.Queue {
  1608. isExist = true
  1609. queue = gpuQueue
  1610. break
  1611. }
  1612. }
  1613. if !isExist {
  1614. log.Error("no such gpuQueue, %s", gpuQueue)
  1615. return queue, errors.New("no such gpuQueue")
  1616. }
  1617. return queue, nil
  1618. }
  1619. func getBenchmarkResourceSpec(resourceSpecID int) (int, error) {
  1620. var id int
  1621. if benchmarkResourceSpecs == nil {
  1622. if err := json.Unmarshal([]byte(setting.BenchmarkResourceSpecs), &benchmarkResourceSpecs); err != nil {
  1623. log.Error("json.Unmarshal BenchmarkResourceSpecs(%s) failed:%v", setting.BenchmarkResourceSpecs, err)
  1624. return id, err
  1625. }
  1626. }
  1627. var isExist bool
  1628. for _, resourceSpec := range benchmarkResourceSpecs.ResourceSpec {
  1629. if resourceSpecID == resourceSpec.Id {
  1630. isExist = true
  1631. id = resourceSpecID
  1632. break
  1633. }
  1634. }
  1635. if !isExist {
  1636. log.Error("no such resourceSpecID, %d", resourceSpecID)
  1637. return id, errors.New("no such resourceSpec")
  1638. }
  1639. return id, nil
  1640. }
  1641. func CloudBrainBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  1642. jobType := form.JobType
  1643. if jobType == string(models.JobTypeBenchmark) {
  1644. BenchMarkAlgorithmCreate(ctx, form)
  1645. } else {
  1646. ModelBenchmarkCreate(ctx, form)
  1647. }
  1648. }
  1649. func BenchMarkAlgorithmCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  1650. ctx.Data["PageIsCloudBrain"] = true
  1651. displayJobName := form.DisplayJobName
  1652. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  1653. image := strings.TrimSpace(form.Image)
  1654. gpuQueue := form.GpuType
  1655. command := cloudbrain.CommandBenchmark
  1656. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  1657. resourceSpecId := cloudbrain.BenchMarkResourceID
  1658. benchmarkTypeID := form.BenchmarkTypeID
  1659. benchmarkChildTypeID := form.BenchmarkChildTypeID
  1660. ctx.Data["description"] = form.Description
  1661. ctx.Data["benchmarkTypeID"] = benchmarkTypeID
  1662. ctx.Data["benchmark_child_types_id_hidden"] = benchmarkChildTypeID
  1663. repo := ctx.Repo.Repository
  1664. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeBenchmark), displayJobName)
  1665. if err == nil {
  1666. if len(tasks) != 0 {
  1667. log.Error("the job name did already exist", ctx.Data["MsgID"])
  1668. cloudBrainNewDataPrepare(ctx)
  1669. ctx.RenderWithErr("the job name did already exist", tplCloudBrainBenchmarkNew, &form)
  1670. return
  1671. }
  1672. } else {
  1673. if !models.IsErrJobNotExist(err) {
  1674. log.Error("system error, %v", err, ctx.Data["MsgID"])
  1675. cloudBrainNewDataPrepare(ctx)
  1676. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1677. return
  1678. }
  1679. }
  1680. if !jobNamePattern.MatchString(jobName) {
  1681. cloudBrainNewDataPrepare(ctx)
  1682. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tplCloudBrainBenchmarkNew, &form)
  1683. return
  1684. }
  1685. childInfo, err := getBenchmarkAttachment(benchmarkTypeID, benchmarkChildTypeID, ctx)
  1686. if err != nil {
  1687. log.Error("getBenchmarkAttachment failed:%v", err, ctx.Data["MsgID"])
  1688. cloudBrainNewDataPrepare(ctx)
  1689. ctx.RenderWithErr("benchmark type error", tplCloudBrainBenchmarkNew, &form)
  1690. return
  1691. }
  1692. _, err = getBenchmarkGpuQueue(gpuQueue)
  1693. if err != nil {
  1694. log.Error("getBenchmarkGpuQueue failed:%v", err, ctx.Data["MsgID"])
  1695. cloudBrainNewDataPrepare(ctx)
  1696. ctx.RenderWithErr("gpu queue error", tplCloudBrainBenchmarkNew, &form)
  1697. return
  1698. }
  1699. _, err = getBenchmarkResourceSpec(resourceSpecId)
  1700. if err != nil {
  1701. log.Error("getBenchmarkResourceSpec failed:%v", err, ctx.Data["MsgID"])
  1702. cloudBrainNewDataPrepare(ctx)
  1703. ctx.RenderWithErr("resource spec error", tplCloudBrainBenchmarkNew, &form)
  1704. return
  1705. }
  1706. count, err := models.GetBenchmarkCountByUserID(ctx.User.ID)
  1707. if err != nil {
  1708. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  1709. cloudBrainNewDataPrepare(ctx)
  1710. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1711. return
  1712. } else {
  1713. if count >= 1 {
  1714. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  1715. cloudBrainNewDataPrepare(ctx)
  1716. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tplCloudBrainBenchmarkNew, &form)
  1717. return
  1718. }
  1719. }
  1720. os.RemoveAll(codePath)
  1721. if err := downloadCode(repo, codePath, cloudbrain.DefaultBranchName); err != nil {
  1722. log.Error("downloadCode failed, %v", err, ctx.Data["MsgID"])
  1723. cloudBrainNewDataPrepare(ctx)
  1724. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1725. return
  1726. }
  1727. if _, err := os.Stat(codePath + "/train.py"); err != nil {
  1728. if os.IsNotExist(err) {
  1729. // file does not exist
  1730. log.Error("train.py does not exist, %v", err, ctx.Data["MsgID"])
  1731. cloudBrainNewDataPrepare(ctx)
  1732. ctx.RenderWithErr("train.py does not exist", tplCloudBrainBenchmarkNew, &form)
  1733. } else {
  1734. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  1735. cloudBrainNewDataPrepare(ctx)
  1736. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1737. }
  1738. return
  1739. } else if _, err := os.Stat(codePath + "/test.py"); err != nil {
  1740. if os.IsNotExist(err) {
  1741. // file does not exist
  1742. log.Error("test.py does not exist, %v", err, ctx.Data["MsgID"])
  1743. cloudBrainNewDataPrepare(ctx)
  1744. ctx.RenderWithErr("test.py does not exist", tplCloudBrainBenchmarkNew, &form)
  1745. } else {
  1746. log.Error("Stat failed, %v", err, ctx.Data["MsgID"])
  1747. cloudBrainNewDataPrepare(ctx)
  1748. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1749. }
  1750. return
  1751. }
  1752. if err := uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  1753. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  1754. cloudBrainNewDataPrepare(ctx)
  1755. ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1756. return
  1757. }
  1758. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  1759. var gpuType string
  1760. for _, gpuInfo := range gpuInfos.GpuInfo {
  1761. if gpuInfo.Queue == gpuQueue {
  1762. gpuType = gpuInfo.Value
  1763. }
  1764. }
  1765. if err := downloadRateCode(repo, jobName, childInfo.Owner, childInfo.RepoName, benchmarkPath, form.BenchmarkCategory, gpuType, ctx.User.Name); err != nil {
  1766. log.Error("downloadRateCode failed, %v", err, ctx.Data["MsgID"])
  1767. //cloudBrainNewDataPrepare(ctx)
  1768. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1769. //return
  1770. }
  1771. if err := uploadCodeToMinio(benchmarkPath+"/", jobName, cloudbrain.BenchMarkMountPath+"/"); err != nil {
  1772. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  1773. //cloudBrainNewDataPrepare(ctx)
  1774. //ctx.RenderWithErr("system error", tplCloudBrainBenchmarkNew, &form)
  1775. //return
  1776. }
  1777. uuid := childInfo.Attachment
  1778. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid)
  1779. if err != nil {
  1780. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  1781. cloudBrainNewDataPrepare(ctx)
  1782. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tplCloudBrainBenchmarkNew, &form)
  1783. return
  1784. }
  1785. req := cloudbrain.GenerateCloudBrainTaskReq{
  1786. Ctx: ctx,
  1787. DisplayJobName: displayJobName,
  1788. JobName: jobName,
  1789. Image: image,
  1790. Command: command,
  1791. Uuids: uuid,
  1792. DatasetNames: datasetNames,
  1793. DatasetInfos: datasetInfos,
  1794. CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  1795. ModelPath: storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  1796. BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"),
  1797. Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  1798. BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"),
  1799. JobType: string(models.JobTypeBenchmark),
  1800. GpuQueue: gpuQueue,
  1801. Description: form.Description,
  1802. BranchName: cloudbrain.DefaultBranchName,
  1803. BootFile: "",
  1804. Params: "",
  1805. CommitID: "",
  1806. BenchmarkTypeID: benchmarkTypeID,
  1807. BenchmarkChildTypeID: benchmarkChildTypeID,
  1808. ResourceSpecId: resourceSpecId,
  1809. }
  1810. err = cloudbrain.GenerateTask(req)
  1811. if err != nil {
  1812. cloudBrainNewDataPrepare(ctx)
  1813. ctx.RenderWithErr(err.Error(), tplCloudBrainBenchmarkNew, &form)
  1814. return
  1815. }
  1816. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  1817. }
  1818. func ModelBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  1819. ctx.Data["PageIsCloudBrain"] = true
  1820. displayJobName := form.DisplayJobName
  1821. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  1822. image := form.Image
  1823. uuid := form.Attachment
  1824. jobType := form.JobType
  1825. gpuQueue := form.GpuType
  1826. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  1827. resourceSpecId := form.ResourceSpecId
  1828. branchName := cloudbrain.DefaultBranchName
  1829. repo := ctx.Repo.Repository
  1830. tpl := tplCloudBrainBenchmarkNew
  1831. command := cloudbrain.Command
  1832. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, jobType, displayJobName)
  1833. if err == nil {
  1834. if len(tasks) != 0 {
  1835. log.Error("the job name did already exist", ctx.Data["MsgID"])
  1836. cloudBrainNewDataPrepare(ctx)
  1837. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  1838. return
  1839. }
  1840. } else {
  1841. if !models.IsErrJobNotExist(err) {
  1842. log.Error("system error, %v", err, ctx.Data["MsgID"])
  1843. cloudBrainNewDataPrepare(ctx)
  1844. ctx.RenderWithErr("system error", tpl, &form)
  1845. return
  1846. }
  1847. }
  1848. if !jobNamePattern.MatchString(displayJobName) {
  1849. cloudBrainNewDataPrepare(ctx)
  1850. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  1851. return
  1852. }
  1853. if jobType != string(models.JobTypeSnn4imagenet) && jobType != string(models.JobTypeBrainScore) {
  1854. log.Error("jobtype error:", jobType, ctx.Data["MsgID"])
  1855. cloudBrainNewDataPrepare(ctx)
  1856. ctx.RenderWithErr("jobtype error", tpl, &form)
  1857. return
  1858. }
  1859. count, err := models.GetBenchmarkCountByUserID(ctx.User.ID)
  1860. if err != nil {
  1861. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  1862. cloudBrainNewDataPrepare(ctx)
  1863. ctx.RenderWithErr("system error", tpl, &form)
  1864. return
  1865. } else {
  1866. if count >= 1 {
  1867. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  1868. cloudBrainNewDataPrepare(ctx)
  1869. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tpl, &form)
  1870. return
  1871. }
  1872. }
  1873. downloadCode(repo, codePath, branchName)
  1874. uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/")
  1875. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  1876. mkModelPath(modelPath)
  1877. uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/")
  1878. snn4imagenetPath := setting.JobPath + jobName + cloudbrain.Snn4imagenetMountPath
  1879. if setting.IsSnn4imagenetEnabled && jobType == string(models.JobTypeSnn4imagenet) {
  1880. downloadRateCode(repo, jobName, setting.Snn4imagenetOwner, setting.Snn4imagenetName, snn4imagenetPath, "", "", ctx.User.Name)
  1881. uploadCodeToMinio(snn4imagenetPath+"/", jobName, cloudbrain.Snn4imagenetMountPath+"/")
  1882. command = fmt.Sprintf(cloudbrain.Snn4imagenetCommand, displayJobName, trimSpaceNewlineInString(form.Description))
  1883. }
  1884. benchmarkChildTypeID := 0
  1885. brainScorePath := setting.JobPath + jobName + cloudbrain.BrainScoreMountPath
  1886. if setting.IsBrainScoreEnabled && jobType == string(models.JobTypeBrainScore) {
  1887. downloadRateCode(repo, jobName, setting.BrainScoreOwner, setting.BrainScoreName, brainScorePath, "", "", ctx.User.Name)
  1888. uploadCodeToMinio(brainScorePath+"/", jobName, cloudbrain.BrainScoreMountPath+"/")
  1889. benchmarkChildTypeID = form.BenchmarkChildTypeID
  1890. command = fmt.Sprintf(cloudbrain.BrainScoreCommand, getBrainRegion(benchmarkChildTypeID), displayJobName, trimSpaceNewlineInString(form.Description))
  1891. }
  1892. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid)
  1893. if err != nil {
  1894. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  1895. cloudBrainNewDataPrepare(ctx)
  1896. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  1897. return
  1898. }
  1899. req := cloudbrain.GenerateCloudBrainTaskReq{
  1900. Ctx: ctx,
  1901. DisplayJobName: displayJobName,
  1902. JobName: jobName,
  1903. Image: image,
  1904. Command: command,
  1905. Uuids: uuid,
  1906. DatasetNames: datasetNames,
  1907. DatasetInfos: datasetInfos,
  1908. CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  1909. ModelPath: storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"),
  1910. BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"),
  1911. Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  1912. BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"),
  1913. JobType: jobType,
  1914. GpuQueue: gpuQueue,
  1915. Description: form.Description,
  1916. BranchName: branchName,
  1917. BootFile: form.BootFile,
  1918. Params: form.Params,
  1919. CommitID: "",
  1920. BenchmarkTypeID: 0,
  1921. BenchmarkChildTypeID: benchmarkChildTypeID,
  1922. ResourceSpecId: resourceSpecId,
  1923. }
  1924. err = cloudbrain.GenerateTask(req)
  1925. if err != nil {
  1926. cloudBrainNewDataPrepare(ctx)
  1927. ctx.RenderWithErr(err.Error(), tpl, &form)
  1928. return
  1929. }
  1930. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  1931. }
  1932. func getBrainRegion(benchmarkChildTypeID int) string {
  1933. values := []string{"V1", "V2", "V4", "IT"}
  1934. return values[benchmarkChildTypeID]
  1935. }
  1936. func trimSpaceNewlineInString(s string) string {
  1937. re := regexp.MustCompile(`\r?\n`)
  1938. return re.ReplaceAllString(s, " ")
  1939. }
  1940. func BenchmarkDel(ctx *context.Context) {
  1941. if err := deleteCloudbrainJob(ctx); err != nil {
  1942. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  1943. ctx.ServerError(err.Error(), err)
  1944. return
  1945. }
  1946. var isAdminPage = ctx.Query("isadminpage")
  1947. var isHomePage = ctx.Query("ishomepage")
  1948. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1949. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1950. } else if isHomePage == "true" {
  1951. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  1952. } else {
  1953. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  1954. }
  1955. }
  1956. func CloudBrainTrainJobNew(ctx *context.Context) {
  1957. err := cloudBrainNewDataPrepare(ctx)
  1958. if err != nil {
  1959. ctx.ServerError("get new train-job info failed", err)
  1960. return
  1961. }
  1962. ctx.HTML(http.StatusOK, tplCloudBrainTrainJobNew)
  1963. }
  1964. func getTrainJobCommand(form auth.CreateCloudBrainForm) (string, error) {
  1965. var command string
  1966. bootFile := strings.TrimSpace(form.BootFile)
  1967. params := form.Params
  1968. if !strings.HasSuffix(bootFile, ".py") {
  1969. log.Error("bootFile(%s) format error", bootFile)
  1970. return command, errors.New("bootFile format error")
  1971. }
  1972. var parameters models.Parameters
  1973. var param string
  1974. if len(params) != 0 {
  1975. err := json.Unmarshal([]byte(params), &parameters)
  1976. if err != nil {
  1977. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  1978. return command, err
  1979. }
  1980. for _, parameter := range parameters.Parameter {
  1981. param += " --" + parameter.Label + "=" + parameter.Value
  1982. }
  1983. }
  1984. command += "python /code/" + bootFile + param + " > " + cloudbrain.ModelMountPath + "/" + form.DisplayJobName + "-" + cloudbrain.LogFile
  1985. return command, nil
  1986. }
  1987. func CloudBrainTrainJobDel(ctx *context.Context) {
  1988. var listType = ctx.Query("listType")
  1989. if err := deleteCloudbrainJob(ctx); err != nil {
  1990. log.Error("deleteCloudbrainJob failed: %v", err, ctx.Data["msgID"])
  1991. ctx.ServerError(err.Error(), err)
  1992. return
  1993. }
  1994. var isAdminPage = ctx.Query("isadminpage")
  1995. var isHomePage = ctx.Query("ishomepage")
  1996. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  1997. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  1998. } else if isHomePage == "true" {
  1999. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  2000. } else {
  2001. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  2002. }
  2003. }
  2004. func GetBenchmarkTypes(ctx *context.Context) *models.BenchmarkTypes {
  2005. var lang = ctx.Locale.Language()
  2006. if benchmarkTypesMap[lang] == nil {
  2007. var val = i18n.Tr(lang, BENCHMARK_TYPE_CODE)
  2008. //use config
  2009. val = setting.BenchmarkTypes
  2010. var tempType *models.BenchmarkTypes
  2011. if err := json.Unmarshal([]byte(val), &tempType); err != nil {
  2012. log.Error("json.Unmarshal BenchmarkTypes(%s) failed:%v", val, err, ctx.Data["MsgID"])
  2013. return &models.BenchmarkTypes{}
  2014. }
  2015. benchmarkTypesMap[lang] = tempType
  2016. }
  2017. return benchmarkTypesMap[lang]
  2018. }