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

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