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