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

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