cgroup.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package worker
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strconv"
  8. "syscall"
  9. "golang.org/x/sys/unix"
  10. "github.com/codeskyblue/go-sh"
  11. )
  12. type cgroupHook struct {
  13. emptyHook
  14. provider mirrorProvider
  15. basePath string
  16. baseGroup string
  17. created bool
  18. }
  19. func newCgroupHook(p mirrorProvider, basePath, baseGroup string) *cgroupHook {
  20. if basePath == "" {
  21. basePath = "/sys/fs/cgroup"
  22. }
  23. if baseGroup == "" {
  24. baseGroup = "tunasync"
  25. }
  26. return &cgroupHook{
  27. provider: p,
  28. basePath: basePath,
  29. baseGroup: baseGroup,
  30. }
  31. }
  32. func (c *cgroupHook) preExec() error {
  33. c.created = true
  34. return sh.Command("cgcreate", "-g", c.Cgroup()).Run()
  35. }
  36. func (c *cgroupHook) postExec() error {
  37. err := c.killAll()
  38. if err != nil {
  39. logger.Error("Error killing tasks: %s", err.Error())
  40. }
  41. c.created = false
  42. return sh.Command("cgdelete", c.Cgroup()).Run()
  43. }
  44. func (c *cgroupHook) Cgroup() string {
  45. name := c.provider.Name()
  46. return fmt.Sprintf("cpu:%s/%s", c.baseGroup, name)
  47. }
  48. func (c *cgroupHook) killAll() error {
  49. if !c.created {
  50. return nil
  51. }
  52. name := c.provider.Name()
  53. taskFile, err := os.Open(filepath.Join(c.basePath, "cpu", c.baseGroup, name, "tasks"))
  54. if err != nil {
  55. return err
  56. }
  57. defer taskFile.Close()
  58. taskList := []int{}
  59. scanner := bufio.NewScanner(taskFile)
  60. for scanner.Scan() {
  61. pid, err := strconv.Atoi(scanner.Text())
  62. if err != nil {
  63. return err
  64. }
  65. taskList = append(taskList, pid)
  66. }
  67. for _, pid := range taskList {
  68. logger.Debug("Killing process: %d", pid)
  69. unix.Kill(pid, syscall.SIGKILL)
  70. }
  71. return nil
  72. }