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.3 kB

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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. }
  80. for i, payload := range result.Payload {
  81. if strings.HasPrefix(result.Payload[i].Place, "192.168") {
  82. result.Payload[i].PlaceView = payload.Place[strings.Index(payload.Place, "/"):len(payload.Place)]
  83. } else {
  84. result.Payload[i].PlaceView = payload.Place
  85. }
  86. }
  87. ctx.Data["images"] = result.Payload
  88. attachs, err := models.GetAllUserAttachments(ctx.User.ID)
  89. if err != nil {
  90. ctx.ServerError("GetAllUserAttachments failed:", err)
  91. return
  92. }
  93. ctx.Data["attachments"] = attachs
  94. ctx.Data["command"] = cloudbrain.Command
  95. ctx.Data["code_path"] = cloudbrain.CodeMountPath
  96. ctx.Data["dataset_path"] = cloudbrain.DataSetMountPath
  97. ctx.Data["model_path"] = cloudbrain.ModelMountPath
  98. ctx.Data["benchmark_path"] = cloudbrain.BenchMarkMountPath
  99. ctx.Data["is_benchmark_enabled"] = setting.IsBenchmarkEnabled
  100. ctx.HTML(200, tplCloudBrainNew)
  101. }
  102. func CloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) {
  103. ctx.Data["PageIsCloudBrain"] = true
  104. jobName := form.JobName
  105. image := form.Image
  106. command := form.Command
  107. uuid := form.Attachment
  108. jobType := form.JobType
  109. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  110. if jobType != string(models.JobTypeBenchmark) && jobType != string(models.JobTypeDebug) {
  111. log.Error("jobtype error:", jobType)
  112. ctx.RenderWithErr("jobtype error", tplCloudBrainNew, &form)
  113. return
  114. }
  115. repo := ctx.Repo.Repository
  116. downloadCode(repo, codePath)
  117. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath
  118. err := os.MkdirAll(modelPath, os.ModePerm)
  119. if err != nil {
  120. ctx.RenderWithErr(err.Error(), tplCloudBrainNew, &form)
  121. return
  122. }
  123. benchmarkPath := setting.JobPath + jobName + cloudbrain.BenchMarkMountPath
  124. if setting.IsBenchmarkEnabled && jobType == string(models.JobTypeBenchmark) {
  125. downloadBenchmarkCode(repo, jobName, benchmarkPath)
  126. }
  127. err = cloudbrain.GenerateTask(ctx, jobName, image, command, uuid, codePath, modelPath, benchmarkPath, jobType)
  128. if err != nil {
  129. ctx.RenderWithErr(err.Error(), tplCloudBrainNew, &form)
  130. return
  131. }
  132. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  133. }
  134. func CloudBrainShow(ctx *context.Context) {
  135. ctx.Data["PageIsCloudBrain"] = true
  136. var jobID = ctx.Params(":jobid")
  137. task, err := models.GetCloudbrainByJobID(jobID)
  138. if err != nil {
  139. ctx.Data["error"] = err.Error()
  140. }
  141. result, err := cloudbrain.GetJob(jobID)
  142. if err != nil {
  143. ctx.Data["error"] = err.Error()
  144. }
  145. if result != nil {
  146. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  147. ctx.Data["result"] = jobRes
  148. taskRoles := jobRes.TaskRoles
  149. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  150. ctx.Data["taskRes"] = taskRes
  151. task.Status = taskRes.TaskStatuses[0].State
  152. task.ContainerID = taskRes.TaskStatuses[0].ContainerID
  153. task.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  154. err = models.UpdateJob(task)
  155. if err != nil {
  156. ctx.Data["error"] = err.Error()
  157. }
  158. }
  159. ctx.Data["task"] = task
  160. ctx.Data["jobID"] = jobID
  161. ctx.HTML(200, tplCloudBrainShow)
  162. }
  163. func CloudBrainDebug(ctx *context.Context) {
  164. var jobID = ctx.Params(":jobid")
  165. task, err := models.GetCloudbrainByJobID(jobID)
  166. if err != nil {
  167. ctx.ServerError("GetCloudbrainByJobID failed", err)
  168. return
  169. }
  170. debugUrl := setting.DebugServerHost + "jpylab_" + task.JobID + "_" + task.SubTaskName
  171. ctx.Redirect(debugUrl)
  172. }
  173. func CloudBrainCommitImage(ctx *context.Context, form auth.CommitImageCloudBrainForm) {
  174. var jobID = ctx.Params(":jobid")
  175. task, err := models.GetCloudbrainByJobID(jobID)
  176. if err != nil {
  177. ctx.JSON(200, map[string]string{
  178. "result_code": "-1",
  179. "error_msg": "GetCloudbrainByJobID failed",
  180. })
  181. return
  182. }
  183. err = cloudbrain.CommitImage(jobID, models.CommitImageParams{
  184. Ip: task.ContainerIp,
  185. TaskContainerId: task.ContainerID,
  186. ImageDescription: form.Description,
  187. ImageTag: form.Tag,
  188. })
  189. if err != nil {
  190. log.Error("CommitImage(%s) failed:", task.JobName, err.Error())
  191. ctx.JSON(200, map[string]string{
  192. "result_code": "-1",
  193. "error_msg": "CommitImage failed",
  194. })
  195. return
  196. }
  197. ctx.JSON(200, map[string]string{
  198. "result_code": "0",
  199. "error_msg": "",
  200. })
  201. }
  202. func CloudBrainStop(ctx *context.Context) {
  203. var jobID = ctx.Params(":jobid")
  204. log.Info(jobID)
  205. task, err := models.GetCloudbrainByJobID(jobID)
  206. if err != nil {
  207. ctx.ServerError("GetCloudbrainByJobID failed", err)
  208. return
  209. }
  210. if task.Status != string(models.JobRunning) {
  211. log.Error("the job(%s) is not running", task.JobName)
  212. ctx.ServerError("the job is not running", errors.New("the job is not running"))
  213. return
  214. }
  215. err = cloudbrain.StopJob(jobID)
  216. if err != nil {
  217. log.Error("StopJob(%s) failed:%v", task.JobName, err.Error())
  218. ctx.ServerError("StopJob failed", err)
  219. return
  220. }
  221. task.Status = string(models.JobStopped)
  222. err = models.UpdateJob(task)
  223. if err != nil {
  224. ctx.ServerError("UpdateJob failed", err)
  225. return
  226. }
  227. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  228. }
  229. func CloudBrainDel(ctx *context.Context) {
  230. var jobID = ctx.Params(":jobid")
  231. task, err := models.GetCloudbrainByJobID(jobID)
  232. if err != nil {
  233. ctx.ServerError("GetCloudbrainByJobID failed", err)
  234. return
  235. }
  236. if task.Status != string(models.JobStopped) {
  237. log.Error("the job(%s) has not been stopped", task.JobName)
  238. ctx.ServerError("the job has not been stopped", errors.New("the job has not been stopped"))
  239. return
  240. }
  241. err = models.DeleteJob(task)
  242. if err != nil {
  243. ctx.ServerError("DeleteJob failed", err)
  244. return
  245. }
  246. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain")
  247. }
  248. func CloudBrainBenchmark(ctx *context.Context) {
  249. var jobID = ctx.Params(":jobid")
  250. _, err := models.GetCloudbrainByJobID(jobID)
  251. if err != nil {
  252. ctx.ServerError("GetCloudbrainByJobID failed", err)
  253. return
  254. }
  255. ctx.Redirect(setting.BenchmarkServerHost)
  256. }
  257. func downloadCode(repo *models.Repository, codePath string) error {
  258. if err := git.Clone(repo.RepoPath(), codePath, git.CloneRepoOptions{}); err != nil {
  259. log.Error("Failed to clone repository: %s (%v)", repo.FullName(), err)
  260. return err
  261. }
  262. return nil
  263. }
  264. func downloadBenchmarkCode(repo *models.Repository, taskName string, benchmarkPath string) error {
  265. err := os.MkdirAll(benchmarkPath, os.ModePerm)
  266. if err != nil {
  267. log.Error("mkdir benchmarkPath failed", err.Error())
  268. return err
  269. }
  270. command := "git clone " + setting.BenchmarkCode + " " + benchmarkPath
  271. cmd := exec.Command("/bin/bash", "-c", command)
  272. output, err := cmd.Output()
  273. log.Info(string(output))
  274. if err != nil {
  275. log.Error("exec.Command(%s) failed:%v", command, err)
  276. return err
  277. }
  278. fileName := benchmarkPath + cloudbrain.TaskInfoName
  279. f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
  280. if err != nil {
  281. log.Error("OpenFile failed", err.Error())
  282. return err
  283. }
  284. defer f.Close()
  285. data, err := json.Marshal(models.TaskInfo{
  286. Username: repo.Owner.Name,
  287. TaskName: taskName,
  288. CodeName: repo.Name,
  289. })
  290. if err != nil {
  291. log.Error("json.Marshal failed", err.Error())
  292. return err
  293. }
  294. _, err = f.Write(data)
  295. if err != nil {
  296. log.Error("WriteString failed", err.Error())
  297. return err
  298. }
  299. return nil
  300. }