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

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