memory_test.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. "path/filepath"
  27. "runtime"
  28. "strings"
  29. "sync"
  30. "sync/atomic"
  31. "testing"
  32. "time"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  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["DataStoreDirectory"] = testDataDirName
  90. modifyConfig["RemoteServerListDownloadFilename"] = filepath.Join(testDataDirName, "server_list_compressed")
  91. modifyConfig["UpgradeDownloadFilename"] = filepath.Join(testDataDirName, "upgrade")
  92. modifyConfig["FetchRemoteServerListRetryPeriodMilliseconds"] = 250
  93. modifyConfig["EstablishTunnelPausePeriodSeconds"] = 1
  94. modifyConfig["ConnectionWorkerPoolSize"] = 10
  95. modifyConfig["DisableLocalSocksProxy"] = true
  96. modifyConfig["DisableLocalHTTPProxy"] = true
  97. modifyConfig["LimitIntensiveConnectionWorkers"] = 5
  98. modifyConfig["LimitMeekBufferSizes"] = true
  99. modifyConfig["StaggerConnectionWorkersMilliseconds"] = 100
  100. modifyConfig["IgnoreHandshakeStatsRegexps"] = true
  101. configJSON, _ = json.Marshal(modifyConfig)
  102. config, err := psiphon.LoadConfig(configJSON)
  103. if err != nil {
  104. t.Fatalf("error processing configuration file: %s", err)
  105. }
  106. err = config.Commit()
  107. if err != nil {
  108. t.Fatalf("error committing configuration file: %s", err)
  109. }
  110. // Don't wait for a tactics request.
  111. applyParameters := map[string]interface{}{
  112. parameters.TacticsWaitPeriod: "1ms",
  113. }
  114. err = config.SetClientParameters("", true, applyParameters)
  115. if err != nil {
  116. t.Fatalf("SetClientParameters failed: %s", err)
  117. }
  118. err = psiphon.OpenDataStore(config)
  119. if err != nil {
  120. t.Fatalf("error initializing datastore: %s", err)
  121. }
  122. defer psiphon.CloseDataStore()
  123. var controller *psiphon.Controller
  124. var controllerCtx context.Context
  125. var controllerStopRunning context.CancelFunc
  126. var controllerWaitGroup *sync.WaitGroup
  127. restartController := make(chan bool, 1)
  128. reconnectTunnel := make(chan bool, 1)
  129. tunnelsEstablished := int32(0)
  130. postActiveTunnelTerminateDelay := 250 * time.Millisecond
  131. testDuration := 2 * time.Minute
  132. memInspectionFrequency := 10 * time.Second
  133. maxInuseBytes := uint64(10 * 1024 * 1024)
  134. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  135. func(notice []byte) {
  136. noticeType, payload, err := psiphon.GetNotice(notice)
  137. if err != nil {
  138. return
  139. }
  140. switch noticeType {
  141. case "Tunnels":
  142. count := int(payload["count"].(float64))
  143. if count > 0 {
  144. atomic.AddInt32(&tunnelsEstablished, 1)
  145. time.Sleep(postActiveTunnelTerminateDelay)
  146. doRestartController := (testMode == testModeRestartController)
  147. if testMode == testModeReconnectAndRestart {
  148. doRestartController = prng.FlipCoin()
  149. }
  150. if doRestartController {
  151. select {
  152. case restartController <- true:
  153. default:
  154. }
  155. } else {
  156. select {
  157. case reconnectTunnel <- true:
  158. default:
  159. }
  160. }
  161. }
  162. case "Info":
  163. message := payload["message"].(string)
  164. if strings.Contains(message, "peak concurrent establish tunnels") {
  165. fmt.Printf("%s, ", message)
  166. } else if strings.Contains(message, "peak concurrent meek establish tunnels") {
  167. fmt.Printf("%s\n", message)
  168. }
  169. }
  170. }))
  171. startController := func() {
  172. controller, err = psiphon.NewController(config)
  173. if err != nil {
  174. t.Fatalf("error creating controller: %s", err)
  175. }
  176. controllerCtx, controllerStopRunning = context.WithCancel(context.Background())
  177. controllerWaitGroup = new(sync.WaitGroup)
  178. controllerWaitGroup.Add(1)
  179. go func() {
  180. defer controllerWaitGroup.Done()
  181. controller.Run(controllerCtx)
  182. }()
  183. }
  184. stopController := func() {
  185. controllerStopRunning()
  186. controllerWaitGroup.Wait()
  187. }
  188. testTimer := time.NewTimer(testDuration)
  189. defer testTimer.Stop()
  190. memInspectionTicker := time.NewTicker(memInspectionFrequency)
  191. lastTunnelsEstablished := int32(0)
  192. startController()
  193. test_loop:
  194. for {
  195. select {
  196. case <-testTimer.C:
  197. break test_loop
  198. case <-memInspectionTicker.C:
  199. var m runtime.MemStats
  200. runtime.ReadMemStats(&m)
  201. inuseBytes := m.HeapInuse + m.StackInuse + m.MSpanInuse + m.MCacheInuse
  202. if inuseBytes > maxInuseBytes {
  203. t.Fatalf("MemStats.*Inuse bytes exceeds limit: %d", inuseBytes)
  204. } else {
  205. n := atomic.LoadInt32(&tunnelsEstablished)
  206. fmt.Printf("Tunnels established: %d, MemStats.*InUse (peak memory in use): %s, MemStats.TotalAlloc (cumulative allocations): %s\n",
  207. n, common.FormatByteCount(inuseBytes), common.FormatByteCount(m.TotalAlloc))
  208. if lastTunnelsEstablished-n >= 0 {
  209. t.Fatalf("expected established tunnels")
  210. }
  211. lastTunnelsEstablished = n
  212. }
  213. case <-reconnectTunnel:
  214. controller.TerminateNextActiveTunnel()
  215. case <-restartController:
  216. stopController()
  217. startController()
  218. }
  219. }
  220. stopController()
  221. }