memory_test.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. "context"
  22. "encoding/json"
  23. "fmt"
  24. "io/ioutil"
  25. "os"
  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. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  36. )
  37. // memory_test is a memory stress test suite that repeatedly reestablishes
  38. // tunnels and restarts the Controller.
  39. //
  40. // runtime.MemStats is used to monitor system memory usage during the test.
  41. //
  42. // These tests are in its own package as its runtime.MemStats checks must not
  43. // be impacted by other test runs. For the same reason, this test doesn't run
  44. // a mock server.
  45. //
  46. // This test is also long-running and _may_ require setting the test flag
  47. // "-timeout" beyond the default of 10 minutes (check the testDuration
  48. // configured below). Update: testDuration is now reduced from 5 to 2 minutes
  49. // since too many iterations -- reconnections -- will impact the ability of
  50. // the client to access the network. Manually adjust testDuration to run a
  51. // tougher stress test.
  52. //
  53. // For the most accurate memory reporting, run each test individually; e.g.,
  54. // go test -run [TestReconnectTunnel|TestRestartController|etc.]
  55. const (
  56. testModeReconnectTunnel = iota
  57. testModeRestartController
  58. testModeReconnectAndRestart
  59. )
  60. func TestReconnectTunnel(t *testing.T) {
  61. runMemoryTest(t, testModeReconnectTunnel)
  62. }
  63. func TestRestartController(t *testing.T) {
  64. runMemoryTest(t, testModeRestartController)
  65. }
  66. func TestReconnectAndRestart(t *testing.T) {
  67. runMemoryTest(t, testModeReconnectAndRestart)
  68. }
  69. func runMemoryTest(t *testing.T, testMode int) {
  70. testDataDirName, err := ioutil.TempDir("", "psiphon-memory-test")
  71. if err != nil {
  72. fmt.Printf("TempDir failed: %s\n", err)
  73. os.Exit(1)
  74. }
  75. defer os.RemoveAll(testDataDirName)
  76. psiphon.SetEmitDiagnosticNotices(true, true)
  77. configJSON, err := ioutil.ReadFile("../controller_test.config")
  78. if err != nil {
  79. // Skip, don't fail, if config file is not present
  80. t.Skipf("error loading configuration file: %s", err)
  81. }
  82. // Most of these fields _must_ be filled in before calling LoadConfig,
  83. // so that they are correctly set into client parameters.
  84. var modifyConfig map[string]interface{}
  85. json.Unmarshal(configJSON, &modifyConfig)
  86. modifyConfig["ClientVersion"] = "999999999"
  87. modifyConfig["TunnelPoolSize"] = 1
  88. modifyConfig["DataRootDirectory"] = testDataDirName
  89. modifyConfig["FetchRemoteServerListRetryPeriodMilliseconds"] = 250
  90. modifyConfig["EstablishTunnelPausePeriodSeconds"] = 1
  91. modifyConfig["ConnectionWorkerPoolSize"] = 10
  92. modifyConfig["DisableLocalSocksProxy"] = true
  93. modifyConfig["DisableLocalHTTPProxy"] = true
  94. modifyConfig["LimitIntensiveConnectionWorkers"] = 5
  95. modifyConfig["LimitMeekBufferSizes"] = true
  96. modifyConfig["StaggerConnectionWorkersMilliseconds"] = 100
  97. modifyConfig["IgnoreHandshakeStatsRegexps"] = true
  98. configJSON, _ = json.Marshal(modifyConfig)
  99. config, err := psiphon.LoadConfig(configJSON)
  100. if err != nil {
  101. t.Fatalf("error processing configuration file: %s", err)
  102. }
  103. err = config.Commit(false)
  104. if err != nil {
  105. t.Fatalf("error committing configuration file: %s", err)
  106. }
  107. // Don't wait for a tactics request.
  108. applyParameters := map[string]interface{}{
  109. parameters.TacticsWaitPeriod: "1ms",
  110. }
  111. err = config.SetParameters("", true, applyParameters)
  112. if err != nil {
  113. t.Fatalf("SetParameters failed: %s", err)
  114. }
  115. err = psiphon.OpenDataStore(config)
  116. if err != nil {
  117. t.Fatalf("error initializing datastore: %s", err)
  118. }
  119. defer psiphon.CloseDataStore()
  120. var controller *psiphon.Controller
  121. var controllerCtx context.Context
  122. var controllerStopRunning context.CancelFunc
  123. var controllerWaitGroup *sync.WaitGroup
  124. restartController := make(chan bool, 1)
  125. reconnectTunnel := make(chan bool, 1)
  126. tunnelsEstablished := int32(0)
  127. postActiveTunnelTerminateDelay := 250 * time.Millisecond
  128. testDuration := 2 * time.Minute
  129. memInspectionFrequency := 10 * time.Second
  130. maxInuseBytes := uint64(10 * 1024 * 1024)
  131. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  132. func(notice []byte) {
  133. noticeType, payload, err := psiphon.GetNotice(notice)
  134. if err != nil {
  135. return
  136. }
  137. switch noticeType {
  138. case "Tunnels":
  139. count := int(payload["count"].(float64))
  140. if count > 0 {
  141. atomic.AddInt32(&tunnelsEstablished, 1)
  142. time.Sleep(postActiveTunnelTerminateDelay)
  143. doRestartController := (testMode == testModeRestartController)
  144. if testMode == testModeReconnectAndRestart {
  145. doRestartController = prng.FlipCoin()
  146. }
  147. if doRestartController {
  148. select {
  149. case restartController <- true:
  150. default:
  151. }
  152. } else {
  153. select {
  154. case reconnectTunnel <- true:
  155. default:
  156. }
  157. }
  158. }
  159. case "Info":
  160. message := payload["message"].(string)
  161. if strings.Contains(message, "peak concurrent establish tunnels") {
  162. fmt.Printf("%s, ", message)
  163. } else if strings.Contains(message, "peak concurrent meek establish tunnels") {
  164. fmt.Printf("%s\n", message)
  165. }
  166. }
  167. }))
  168. startController := func() {
  169. controller, err = psiphon.NewController(config)
  170. if err != nil {
  171. t.Fatalf("error creating controller: %s", err)
  172. }
  173. controllerCtx, controllerStopRunning = context.WithCancel(context.Background())
  174. controllerWaitGroup = new(sync.WaitGroup)
  175. controllerWaitGroup.Add(1)
  176. go func() {
  177. defer controllerWaitGroup.Done()
  178. controller.Run(controllerCtx)
  179. }()
  180. }
  181. stopController := func() {
  182. controllerStopRunning()
  183. controllerWaitGroup.Wait()
  184. }
  185. testTimer := time.NewTimer(testDuration)
  186. defer testTimer.Stop()
  187. memInspectionTicker := time.NewTicker(memInspectionFrequency)
  188. lastTunnelsEstablished := int32(0)
  189. startController()
  190. test_loop:
  191. for {
  192. select {
  193. case <-testTimer.C:
  194. break test_loop
  195. case <-memInspectionTicker.C:
  196. var m runtime.MemStats
  197. runtime.ReadMemStats(&m)
  198. inuseBytes := m.HeapInuse + m.StackInuse + m.MSpanInuse + m.MCacheInuse
  199. if inuseBytes > maxInuseBytes {
  200. t.Fatalf("MemStats.*Inuse bytes exceeds limit: %d", inuseBytes)
  201. } else {
  202. n := atomic.LoadInt32(&tunnelsEstablished)
  203. fmt.Printf("Tunnels established: %d, MemStats.*InUse (peak memory in use): %s, MemStats.TotalAlloc (cumulative allocations): %s\n",
  204. n, common.FormatByteCount(inuseBytes), common.FormatByteCount(m.TotalAlloc))
  205. if lastTunnelsEstablished-n >= 0 {
  206. t.Fatalf("expected established tunnels")
  207. }
  208. lastTunnelsEstablished = n
  209. }
  210. case <-reconnectTunnel:
  211. controller.TerminateNextActiveTunnel()
  212. case <-restartController:
  213. stopController()
  214. startController()
  215. }
  216. }
  217. stopController()
  218. }