2
0

cgroup_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package worker
  2. import (
  3. "io/ioutil"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "testing"
  8. "time"
  9. . "github.com/smartystreets/goconvey/convey"
  10. )
  11. func TestCgroup(t *testing.T) {
  12. Convey("Cgroup Should Work", t, func(ctx C) {
  13. tmpDir, err := ioutil.TempDir("", "tunasync")
  14. defer os.RemoveAll(tmpDir)
  15. So(err, ShouldBeNil)
  16. cmdScript := filepath.Join(tmpDir, "cmd.sh")
  17. daemonScript := filepath.Join(tmpDir, "daemon.sh")
  18. tmpFile := filepath.Join(tmpDir, "log_file")
  19. bgPidfile := filepath.Join(tmpDir, "bg.pid")
  20. c := cmdConfig{
  21. name: "tuna-cgroup",
  22. upstreamURL: "http://mirrors.tuna.moe/",
  23. command: cmdScript + " " + daemonScript,
  24. workingDir: tmpDir,
  25. logDir: tmpDir,
  26. logFile: tmpFile,
  27. interval: 600 * time.Second,
  28. env: map[string]string{
  29. "BG_PIDFILE": bgPidfile,
  30. },
  31. }
  32. cmdScriptContent := `#!/bin/bash
  33. redirect-std() {
  34. [[ -t 0 ]] && exec </dev/null
  35. [[ -t 1 ]] && exec >/dev/null
  36. [[ -t 2 ]] && exec 2>/dev/null
  37. }
  38. # close all non-std* fds
  39. close-fds() {
  40. eval exec {3..255}\>\&-
  41. }
  42. # full daemonization of external command with setsid
  43. daemonize() {
  44. (
  45. redirect-std
  46. cd /
  47. close-fds
  48. exec setsid "$@"
  49. ) &
  50. }
  51. echo $$
  52. daemonize $@
  53. sleep 5
  54. `
  55. daemonScriptContent := `#!/bin/bash
  56. echo $$ > $BG_PIDFILE
  57. sleep 30
  58. `
  59. err = ioutil.WriteFile(cmdScript, []byte(cmdScriptContent), 0755)
  60. So(err, ShouldBeNil)
  61. err = ioutil.WriteFile(daemonScript, []byte(daemonScriptContent), 0755)
  62. So(err, ShouldBeNil)
  63. provider, err := newCmdProvider(c)
  64. So(err, ShouldBeNil)
  65. cg := newCgroupHook(provider, "/sys/fs/cgroup", "tunasync")
  66. provider.AddHook(cg)
  67. err = cg.preExec()
  68. So(err, ShouldBeNil)
  69. go func() {
  70. err = provider.Run()
  71. ctx.So(err, ShouldNotBeNil)
  72. }()
  73. time.Sleep(1 * time.Second)
  74. // Deamon should be started
  75. daemonPidBytes, err := ioutil.ReadFile(bgPidfile)
  76. So(err, ShouldBeNil)
  77. daemonPid := strings.Trim(string(daemonPidBytes), " \n")
  78. logger.Debug("daemon pid: %s", daemonPid)
  79. procDir := filepath.Join("/proc", daemonPid)
  80. _, err = os.Stat(procDir)
  81. So(err, ShouldBeNil)
  82. err = provider.Terminate()
  83. So(err, ShouldBeNil)
  84. // Deamon won't be killed
  85. _, err = os.Stat(procDir)
  86. So(err, ShouldBeNil)
  87. // Deamon can be killed by cgroup killer
  88. cg.postExec()
  89. _, err = os.Stat(procDir)
  90. So(os.IsNotExist(err), ShouldBeTrue)
  91. })
  92. }