memory_test.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. /*
  2. * Copyright (c) 2017, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package memory_test
  20. import (
  21. "encoding/json"
  22. "fmt"
  23. "io/ioutil"
  24. "os"
  25. "path/filepath"
  26. "runtime"
  27. "strings"
  28. "sync"
  29. "sync/atomic"
  30. "testing"
  31. "time"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  34. )
  35. // memory_test is a memory stress test suite that repeatedly
  36. // reestablishes tunnels and restarts the Controller.
  37. //
  38. // runtime.MemStats is used to monitor system memory usage
  39. // during the test.
  40. //
  41. // These tests are in its own package as its runtime.MemStats
  42. // checks must not be impacted by other test runs; this
  43. // test is also long-running and _may_ require setting the
  44. // test flag "-timeout" beyond the default of 10 minutes
  45. // (check the testDuration configured below).
  46. //
  47. // For the most accurate memory reporting, run each test
  48. // individually; e.g.,
  49. // go test -run [TestReconnectTunnel|TestRestartController|etc.]
  50. const (
  51. testModeReconnectTunnel = iota
  52. testModeRestartController
  53. testModeReconnectAndRestart
  54. )
  55. func TestReconnectTunnel(t *testing.T) {
  56. runMemoryTest(t, testModeReconnectTunnel)
  57. }
  58. func TestRestartController(t *testing.T) {
  59. runMemoryTest(t, testModeRestartController)
  60. }
  61. func TestReconnectAndRestart(t *testing.T) {
  62. runMemoryTest(t, testModeReconnectAndRestart)
  63. }
  64. func runMemoryTest(t *testing.T, testMode int) {
  65. testDataDirName, err := ioutil.TempDir("", "psiphon-memory-test")
  66. if err != nil {
  67. fmt.Printf("TempDir failed: %s\n", err)
  68. os.Exit(1)
  69. }
  70. defer os.RemoveAll(testDataDirName)
  71. os.Remove(filepath.Join(testDataDirName, psiphon.DATA_STORE_FILENAME))
  72. psiphon.SetEmitDiagnosticNotices(true)
  73. configJSON, err := ioutil.ReadFile("../controller_test.config")
  74. if err != nil {
  75. // Skip, don't fail, if config file is not present
  76. t.Skipf("error loading configuration file: %s", err)
  77. }
  78. // These fields must be filled in before calling LoadConfig
  79. var modifyConfig map[string]interface{}
  80. json.Unmarshal(configJSON, &modifyConfig)
  81. modifyConfig["DataStoreDirectory"] = testDataDirName
  82. modifyConfig["RemoteServerListDownloadFilename"] = filepath.Join(testDataDirName, "server_list_compressed")
  83. modifyConfig["UpgradeDownloadFilename"] = filepath.Join(testDataDirName, "upgrade")
  84. configJSON, _ = json.Marshal(modifyConfig)
  85. config, err := psiphon.LoadConfig(configJSON)
  86. if err != nil {
  87. t.Fatalf("error processing configuration file: %s", err)
  88. }
  89. postActiveTunnelTerminateDelay := 250 * time.Millisecond
  90. testDuration := 5 * time.Minute
  91. memInspectionFrequency := 10 * time.Second
  92. maxSysMemory := uint64(11 * 1024 * 1024)
  93. config.ClientVersion = "999999999"
  94. config.TunnelPoolSize = 1
  95. fetchRemoteServerListRetryPeriodSeconds := 0
  96. config.FetchRemoteServerListRetryPeriodSeconds = &fetchRemoteServerListRetryPeriodSeconds
  97. establishTunnelPausePeriodSeconds := 1
  98. config.EstablishTunnelPausePeriodSeconds = &establishTunnelPausePeriodSeconds
  99. config.TunnelProtocol = ""
  100. config.DisableLocalSocksProxy = true
  101. config.DisableLocalHTTPProxy = true
  102. config.ConnectionWorkerPoolSize = 10
  103. config.LimitMeekConnectionWorkers = 5
  104. config.LimitMeekBufferSizes = true
  105. config.StaggerConnectionWorkersMilliseconds = 100
  106. config.IgnoreHandshakeStatsRegexps = true
  107. err = psiphon.InitDataStore(config)
  108. if err != nil {
  109. t.Fatalf("error initializing datastore: %s", err)
  110. }
  111. var controller *psiphon.Controller
  112. var controllerShutdown chan struct{}
  113. var controllerWaitGroup *sync.WaitGroup
  114. restartController := make(chan bool, 1)
  115. reconnectTunnel := make(chan bool, 1)
  116. tunnelsEstablished := int32(0)
  117. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  118. func(notice []byte) {
  119. noticeType, payload, err := psiphon.GetNotice(notice)
  120. if err != nil {
  121. return
  122. }
  123. switch noticeType {
  124. case "Tunnels":
  125. count := int(payload["count"].(float64))
  126. if count > 0 {
  127. atomic.AddInt32(&tunnelsEstablished, 1)
  128. time.Sleep(postActiveTunnelTerminateDelay)
  129. doRestartController := (testMode == testModeRestartController)
  130. if testMode == testModeReconnectAndRestart {
  131. doRestartController = common.FlipCoin()
  132. }
  133. if doRestartController {
  134. select {
  135. case restartController <- true:
  136. default:
  137. }
  138. } else {
  139. select {
  140. case reconnectTunnel <- true:
  141. default:
  142. }
  143. }
  144. }
  145. case "Info":
  146. message := payload["message"].(string)
  147. if strings.Contains(message, "peak concurrent establish tunnels") {
  148. fmt.Printf("%s, ", message)
  149. } else if strings.Contains(message, "peak concurrent meek establish tunnels") {
  150. fmt.Printf("%s\n", message)
  151. }
  152. }
  153. }))
  154. startController := func() {
  155. controller, err = psiphon.NewController(config)
  156. if err != nil {
  157. t.Fatalf("error creating controller: %s", err)
  158. }
  159. controllerShutdown = make(chan struct{})
  160. controllerWaitGroup = new(sync.WaitGroup)
  161. controllerWaitGroup.Add(1)
  162. go func() {
  163. defer controllerWaitGroup.Done()
  164. controller.Run(controllerShutdown)
  165. }()
  166. }
  167. stopController := func() {
  168. close(controllerShutdown)
  169. controllerWaitGroup.Wait()
  170. }
  171. testTimer := time.NewTimer(testDuration)
  172. memInspectionTicker := time.NewTicker(memInspectionFrequency)
  173. lastTunnelsEstablished := int32(0)
  174. startController()
  175. test_loop:
  176. for {
  177. select {
  178. case <-testTimer.C:
  179. break test_loop
  180. case <-memInspectionTicker.C:
  181. var m runtime.MemStats
  182. runtime.ReadMemStats(&m)
  183. if m.Sys > maxSysMemory {
  184. t.Fatalf("sys memory exceeds limit: %d", m.Sys)
  185. } else {
  186. n := atomic.LoadInt32(&tunnelsEstablished)
  187. fmt.Printf("Tunnels established: %d, MemStats.Sys (peak system memory used): %s, MemStats.TotalAlloc (cumulative allocations): %s\n",
  188. n, common.FormatByteCount(m.Sys), common.FormatByteCount(m.TotalAlloc))
  189. if lastTunnelsEstablished-n >= 0 {
  190. t.Fatalf("expected established tunnels")
  191. }
  192. lastTunnelsEstablished = n
  193. }
  194. case <-reconnectTunnel:
  195. controller.TerminateNextActiveTunnel()
  196. case <-restartController:
  197. stopController()
  198. startController()
  199. }
  200. }
  201. stopController()
  202. }