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

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