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