memory_test.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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. )
  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. os.Remove(filepath.Join(testDataDirName, psiphon.DATA_STORE_FILENAME))
  77. psiphon.SetEmitDiagnosticNotices(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["LimitMeekConnectionWorkers"] = 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.InitDataStore(config)
  119. if err != nil {
  120. t.Fatalf("error initializing datastore: %s", err)
  121. }
  122. var controller *psiphon.Controller
  123. var controllerCtx context.Context
  124. var controllerStopRunning context.CancelFunc
  125. var controllerWaitGroup *sync.WaitGroup
  126. restartController := make(chan bool, 1)
  127. reconnectTunnel := make(chan bool, 1)
  128. tunnelsEstablished := int32(0)
  129. postActiveTunnelTerminateDelay := 250 * time.Millisecond
  130. testDuration := 2 * time.Minute
  131. memInspectionFrequency := 10 * time.Second
  132. maxSysMemory := uint64(11 * 1024 * 1024)
  133. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  134. func(notice []byte) {
  135. noticeType, payload, err := psiphon.GetNotice(notice)
  136. if err != nil {
  137. return
  138. }
  139. switch noticeType {
  140. case "Tunnels":
  141. count := int(payload["count"].(float64))
  142. if count > 0 {
  143. atomic.AddInt32(&tunnelsEstablished, 1)
  144. time.Sleep(postActiveTunnelTerminateDelay)
  145. doRestartController := (testMode == testModeRestartController)
  146. if testMode == testModeReconnectAndRestart {
  147. doRestartController = common.FlipCoin()
  148. }
  149. if doRestartController {
  150. select {
  151. case restartController <- true:
  152. default:
  153. }
  154. } else {
  155. select {
  156. case reconnectTunnel <- true:
  157. default:
  158. }
  159. }
  160. }
  161. case "Info":
  162. message := payload["message"].(string)
  163. if strings.Contains(message, "peak concurrent establish tunnels") {
  164. fmt.Printf("%s, ", message)
  165. } else if strings.Contains(message, "peak concurrent meek establish tunnels") {
  166. fmt.Printf("%s\n", message)
  167. }
  168. }
  169. }))
  170. startController := func() {
  171. controller, err = psiphon.NewController(config)
  172. if err != nil {
  173. t.Fatalf("error creating controller: %s", err)
  174. }
  175. controllerCtx, controllerStopRunning = context.WithCancel(context.Background())
  176. controllerWaitGroup = new(sync.WaitGroup)
  177. controllerWaitGroup.Add(1)
  178. go func() {
  179. defer controllerWaitGroup.Done()
  180. controller.Run(controllerCtx)
  181. }()
  182. }
  183. stopController := func() {
  184. controllerStopRunning()
  185. controllerWaitGroup.Wait()
  186. }
  187. testTimer := time.NewTimer(testDuration)
  188. defer testTimer.Stop()
  189. memInspectionTicker := time.NewTicker(memInspectionFrequency)
  190. lastTunnelsEstablished := int32(0)
  191. startController()
  192. test_loop:
  193. for {
  194. select {
  195. case <-testTimer.C:
  196. break test_loop
  197. case <-memInspectionTicker.C:
  198. var m runtime.MemStats
  199. runtime.ReadMemStats(&m)
  200. if m.Sys > maxSysMemory {
  201. t.Fatalf("sys memory exceeds limit: %d", m.Sys)
  202. } else {
  203. n := atomic.LoadInt32(&tunnelsEstablished)
  204. fmt.Printf("Tunnels established: %d, MemStats.Sys (peak system memory used): %s, MemStats.TotalAlloc (cumulative allocations): %s\n",
  205. n, common.FormatByteCount(m.Sys), common.FormatByteCount(m.TotalAlloc))
  206. if lastTunnelsEstablished-n >= 0 {
  207. t.Fatalf("expected established tunnels")
  208. }
  209. lastTunnelsEstablished = n
  210. }
  211. case <-reconnectTunnel:
  212. controller.TerminateNextActiveTunnel()
  213. case <-restartController:
  214. stopController()
  215. startController()
  216. }
  217. }
  218. stopController()
  219. }