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