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