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