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

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