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