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