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