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

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