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 12 kB

5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 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
5 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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. package repo
  2. import (
  3. "code.gitea.io/gitea/modules/git"
  4. "encoding/json"
  5. "errors"
  6. "os"
  7. "os/exec"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/auth"
  13. "code.gitea.io/gitea/modules/base"
  14. "code.gitea.io/gitea/modules/cloudbrain"
  15. "code.gitea.io/gitea/modules/context"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/setting"
  18. )
  19. const (
  20. tplCloudBrainIndex base.TplName = "repo/cloudbrain/index"
  21. tplCloudBrainNew base.TplName = "repo/cloudbrain/new"
  22. tplCloudBrainShow base.TplName = "repo/cloudbrain/show"
  23. tplCloudBrainShowModels base.TplName = "repo/cloudbrain/show_models"
  24. )
  25. var (
  26. gpuInfos *models.GpuInfos
  27. categories *models.Categories
  28. )
  29. // MustEnableDataset check if repository enable internal cb
  30. func MustEnableCloudbrain(ctx *context.Context) {
  31. if !ctx.Repo.CanRead(models.UnitTypeCloudBrain) {
  32. ctx.NotFound("MustEnableCloudbrain", nil)
  33. return
  34. }
  35. }
  36. func CloudBrainIndex(ctx *context.Context) {
  37. MustEnableCloudbrain(ctx)
  38. repo := ctx.Repo.Repository
  39. page := ctx.QueryInt("page")
  40. if page <= 0 {
  41. page = 1
  42. }
  43. ciTasks, count, err := models.Cloudbrains(&models.CloudbrainsOptions{
  44. ListOptions: models.ListOptions{
  45. Page: page,
  46. PageSize: setting.UI.IssuePagingNum,
  47. },
  48. RepoID: repo.ID,
  49. Type: models.TypeCloudBrainOne,
  50. })
  51. if err != nil {
  52. ctx.ServerError("Cloudbrain", err)
  53. return
  54. }
  55. timestamp := time.Now().Unix()
  56. for i, task := range ciTasks {
  57. if task.Status == string(models.JobRunning) && (timestamp-int64(task.CreatedUnix) > 30) {
  58. ciTasks[i].CanDebug = true
  59. } else {
  60. ciTasks[i].CanDebug = false
  61. }
  62. }
  63. pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5)
  64. pager.SetDefaultParams(ctx)
  65. ctx.Data["Page"] = pager
  66. ctx.Data["PageIsCloudBrain"] = true
  67. ctx.Data["Tasks"] = ciTasks
  68. ctx.HTML(200, tplCloudBrainIndex)
  69. }
  70. func cutString(str string, lens int) string {
  71. if len(str) < lens {
  72. return str
  73. }
  74. return str[:lens]
  75. }
  76. func CloudBrainNew(ctx *context.Context) {
  77. ctx.Data["PageIsCloudBrain"] = true
  78. t := time.Now()
  79. var jobName = cutString(ctx.User.Name, 5) + t.Format("2006010215") + strconv.Itoa(int(t.Unix()))[5:]
  80. ctx.Data["job_name"] = jobName
  81. result, err := cloudbrain.GetImages()
  82. if err != nil {
  83. ctx.Data["error"] = err.Error()
  84. log.Error("cloudbrain.GetImages failed:", err.Error())
  85. }
  86. for i, payload := range result.Payload.ImageInfo {
  87. if strings.HasPrefix(result.Payload.ImageInfo[i].Place, "192.168") {
  88. result.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  89. } else {
  90. result.Payload.ImageInfo[i].PlaceView = payload.Place
  91. }
  92. }
  93. ctx.Data["images"] = result.Payload.ImageInfo
  94. resultPublic, err := cloudbrain.GetPublicImages()
  95. if err != nil {
  96. ctx.Data["error"] = err.Error()
  97. log.Error("cloudbrain.GetPublicImages failed:", err.Error())
  98. }
  99. for i, payload := range resultPublic.Payload.ImageInfo {
  100. if strings.HasPrefix(resultPublic.Payload.ImageInfo[i].Place, "192.168") {
  101. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  102. } else {
  103. resultPublic.Payload.ImageInfo[i].PlaceView = payload.Place
  104. }
  105. }
  106. ctx.Data["public_images"] = resultPublic.Payload.ImageInfo
  107. attachs, err := models.GetAllUserAttachments(ctx.User.ID)
  108. if err != nil {
  109. ctx.ServerError("GetAllUserAttachments failed:", err)
  110. return
  111. }
  112. ctx.Data["attachments"] = attachs
  113. ctx.Data["command"] = cloudbrain.Command
  114. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  115. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  116. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  117. ctx.Data["benchmark_path"] = cloudbrain.BenchMarkMountPath
  118. ctx.Data["is_benchmark_enabled"] = setting.IsBenchmarkEnabled
  119. if categories == nil {
  120. json.Unmarshal([]byte(setting.BenchmarkCategory), &categories)
  121. }
  122. ctx.Data["benchmark_categories"] = categories.Category
  123. if gpuInfos == nil {
  124. json.Unmarshal([]byte(setting.GpuTypes), &gpuInfos)
  125. }
  126. ctx.Data["gpu_types"] = gpuInfos.GpuInfo
  127. ctx.Data["snn4imagenet_path"] = cloudbrain.Snn4imagenetMountPath
  128. ctx.Data["is_snn4imagenet_enabled"] = setting.IsSnn4imagenetEnabled
  129. ctx.HTML(200, tplCloudBrainNew)
  130. }
  131. func CloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  132. ctx.Data["PageIsCloudBrain"] = true
  133. jobName := form.JobName
  134. image := form.Image
  135. command := form.Command
  136. uuid := form.Attachment
  137. jobType := form.JobType
  138. gpuQueue := setting.JobType
  139. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  140. if jobType != string(models.JobTypeBenchmark) && jobType != string(models.JobTypeDebug) && jobType != string(models.JobTypeSnn4imagenet) {
  141. log.Error("jobtype error:", jobType)
  142. ctx.RenderWithErr("jobtype error", tplCloudBrainNew, &form)
  143. return
  144. }
  145. repo := ctx.Repo.Repository
  146. downloadCode(repo, codePath)
  147. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath
  148. err := os.MkdirAll(modelPath, os.ModePerm)
  149. if err != nil {
  150. ctx.RenderWithErr(err.Error(), tplCloudBrainNew, &form)
  151. return
  152. }
  153. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  154. if setting.IsBenchmarkEnabled && jobType == string(models.JobTypeBenchmark) {
  155. gpuQueue = form.GpuType
  156. var gpuType string
  157. for _, gpuInfo := range gpuInfos.GpuInfo {
  158. if gpuInfo.Queue == gpuQueue {
  159. gpuType = gpuInfo.Value
  160. }
  161. }
  162. downloadRateCode(repo, jobName, setting.BenchmarkCode, benchmarkPath, form.BenchmarkCategory, gpuType)
  163. }
  164. snn4imagenetPath := setting.JobPath + jobName + cloudbrain.Snn4imagenetMountPath
  165. if setting.IsSnn4imagenetEnabled && jobType == string(models.JobTypeSnn4imagenet) {
  166. downloadRateCode(repo, jobName, setting.Snn4imagenetCode, snn4imagenetPath, "", "")
  167. }
  168. err = cloudbrain.GenerateTask(ctx, jobName, image, command, uuid, codePath, modelPath, benchmarkPath, snn4imagenetPath, jobType, gpuQueue)
  169. if err != nil {
  170. ctx.RenderWithErr(err.Error(), tplCloudBrainNew, &form)
  171. return
  172. }
  173. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  174. }
  175. func CloudBrainShow(ctx *context.Context) {
  176. ctx.Data["PageIsCloudBrain"] = true
  177. var jobID = ctx.Params(":jobid")
  178. task, err := models.GetCloudbrainByJobID(jobID)
  179. if err != nil {
  180. ctx.Data["error"] = err.Error()
  181. }
  182. result, err := cloudbrain.GetJob(jobID)
  183. if err != nil {
  184. ctx.Data["error"] = err.Error()
  185. }
  186. if result != nil {
  187. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  188. ctx.Data["result"] = jobRes
  189. taskRoles := jobRes.TaskRoles
  190. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  191. ctx.Data["taskRes"] = taskRes
  192. task.Status = taskRes.TaskStatuses[0].State
  193. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  194. task.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  195. err = models.UpdateJob(task)
  196. if err != nil {
  197. ctx.Data["error"] = err.Error()
  198. }
  199. }
  200. ctx.Data["task"] = task
  201. ctx.Data["jobID"] = jobID
  202. ctx.HTML(200, tplCloudBrainShow)
  203. }
  204. func CloudBrainDebug(ctx *context.Context) {
  205. var jobID = ctx.Params(":jobid")
  206. task, err := models.GetCloudbrainByJobID(jobID)
  207. if err != nil {
  208. ctx.ServerError("GetCloudbrainByJobID failed", err)
  209. return
  210. }
  211. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  212. ctx.Redirect(debugUrl)
  213. }
  214. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  215. var jobID = ctx.Params(":jobid")
  216. task, err := models.GetCloudbrainByJobID(jobID)
  217. if err != nil {
  218. ctx.JSON(200, map[string]string{
  219. "result_code": "-1",
  220. "error_msg": "GetCloudbrainByJobID failed",
  221. })
  222. return
  223. }
  224. err = cloudbrain.CommitImage(jobID, models.CommitImageParams{
  225. Ip: task.ContainerIp,
  226. TaskContainerId: task.ContainerID,
  227. ImageDescription: form.Description,
  228. ImageTag: form.Tag,
  229. })
  230. if err != nil {
  231. log.Error("CommitImage(%s) failed:", task.JobName, err.Error())
  232. ctx.JSON(200, map[string]string{
  233. "result_code": "-1",
  234. "error_msg": "CommitImage failed",
  235. })
  236. return
  237. }
  238. ctx.JSON(200, map[string]string{
  239. "result_code": "0",
  240. "error_msg": "",
  241. })
  242. }
  243. func CloudBrainStop(ctx *context.Context) {
  244. var jobID = ctx.Params(":jobid")
  245. task, err := models.GetCloudbrainByJobID(jobID)
  246. if err != nil {
  247. ctx.ServerError("GetCloudbrainByJobID failed", err)
  248. return
  249. }
  250. if task.Status == string(models.JobStopped) {
  251. log.Error("the job(%s) has been stopped", task.JobName)
  252. ctx.ServerError("the job has been stopped", errors.New("the job has been stopped"))
  253. return
  254. }
  255. err = cloudbrain.StopJob(jobID)
  256. if err != nil {
  257. log.Error("StopJob(%s) failed:%v", task.JobName, err.Error())
  258. ctx.ServerError("StopJob failed", err)
  259. return
  260. }
  261. task.Status = string(models.JobStopped)
  262. err = models.UpdateJob(task)
  263. if err != nil {
  264. ctx.ServerError("UpdateJob failed", err)
  265. return
  266. }
  267. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  268. }
  269. func CloudBrainDel(ctx *context.Context) {
  270. var jobID = ctx.Params(":jobid")
  271. task, err := models.GetCloudbrainByJobID(jobID)
  272. if err != nil {
  273. ctx.ServerError("GetCloudbrainByJobID failed", err)
  274. return
  275. }
  276. if task.Status != string(models.JobStopped) {
  277. log.Error("the job(%s) has not been stopped", task.JobName)
  278. ctx.ServerError("the job has not been stopped", errors.New("the job has not been stopped"))
  279. return
  280. }
  281. err = models.DeleteJob(task)
  282. if err != nil {
  283. ctx.ServerError("DeleteJob failed", err)
  284. return
  285. }
  286. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  287. }
  288. func CloudBrainGetModels(ctx *context.Context) {
  289. ctx.Data["PageIsCloudBrain"] = true
  290. var jobID = ctx.Params(":jobid")
  291. task, err := models.GetCloudbrainByJobID(jobID)
  292. if err != nil {
  293. log.Error("no such job!")
  294. ctx.RenderWithErr("no such job!", tplCloudBrainIndex, nil)
  295. return
  296. }
  297. ctx.Data["task"] = task
  298. ctx.Data["jobID"] = jobID
  299. ctx.HTML(200, tplCloudBrainShowModels)
  300. }
  301. func GetRate(ctx *context.Context) {
  302. var jobID = ctx.Params(":jobid")
  303. job, err := models.GetCloudbrainByJobID(jobID)
  304. if err != nil {
  305. ctx.ServerError("GetCloudbrainByJobID failed", err)
  306. return
  307. }
  308. if job.JobType == string(models.JobTypeBenchmark) {
  309. ctx.Redirect(setting.BenchmarkServerHost)
  310. } else if job.JobType == string(models.JobTypeSnn4imagenet) {
  311. ctx.Redirect(setting.Snn4imagenetServerHost)
  312. } else {
  313. log.Error("JobType error:", job.JobType)
  314. }
  315. }
  316. func downloadCode(repo *models.Repository, codePath string) error {
  317. if err := git.Clone(repo.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  318. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  319. return err
  320. }
  321. return nil
  322. }
  323. func downloadRateCode(repo *models.Repository, taskName, gitPath, codePath, benchmarkCategory, gpuType string) error {
  324. err := os.MkdirAll(codePath, os.ModePerm)
  325. if err != nil {
  326. log.Error("mkdir codePath failed", err.Error())
  327. return err
  328. }
  329. command := "git clone " + gitPath + " " + codePath
  330. cmd := exec.Command("/bin/bash", "-c", command)
  331. output, err := cmd.Output()
  332. log.Info(string(output))
  333. if err != nil {
  334. log.Error("exec.Command(%s) failed:%v", command, err)
  335. return err
  336. }
  337. fileName := codePath + cloudbrain.TaskInfoName
  338. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  339. if err != nil {
  340. log.Error("OpenFile failed", err.Error())
  341. return err
  342. }
  343. defer f.Close()
  344. data, err := json.Marshal(models.TaskInfo{
  345. Username: repo.Owner.Name,
  346. TaskName: taskName,
  347. CodeName: repo.Name,
  348. BenchmarkCategory: strings.Split(benchmarkCategory, ","),
  349. CodeLink: strings.TrimSuffix(repo.CloneLink().HTTPS, ".git"),
  350. GpuType: gpuType,
  351. })
  352. if err != nil {
  353. log.Error("json.Marshal failed", err.Error())
  354. return err
  355. }
  356. _, err = f.Write(data)
  357. if err != nil {
  358. log.Error("WriteString failed", err.Error())
  359. return err
  360. }
  361. return nil
  362. }