memory_test.go 7.5 KB

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