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

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