memory_test.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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. )
  36. // memory_test is a memory stress test suite that repeatedly
  37. // reestablishes tunnels and restarts the Controller.
  38. //
  39. // runtime.MemStats is used to monitor system memory usage
  40. // during the test.
  41. //
  42. // These tests are in its own package as its runtime.MemStats
  43. // checks must not be impacted by other test runs; this
  44. // test is also long-running and _may_ require setting the
  45. // test flag "-timeout" beyond the default of 10 minutes
  46. // (check the testDuration configured below).
  47. //
  48. // For the most accurate memory reporting, run each test
  49. // individually; e.g.,
  50. // go test -run [TestReconnectTunnel|TestRestartController|etc.]
  51. const (
  52. testModeReconnectTunnel = iota
  53. testModeRestartController
  54. testModeReconnectAndRestart
  55. )
  56. func TestReconnectTunnel(t *testing.T) {
  57. runMemoryTest(t, testModeReconnectTunnel)
  58. }
  59. func TestRestartController(t *testing.T) {
  60. runMemoryTest(t, testModeRestartController)
  61. }
  62. func TestReconnectAndRestart(t *testing.T) {
  63. runMemoryTest(t, testModeReconnectAndRestart)
  64. }
  65. func runMemoryTest(t *testing.T, testMode int) {
  66. testDataDirName, err := ioutil.TempDir("", "psiphon-memory-test")
  67. if err != nil {
  68. fmt.Printf("TempDir failed: %s\n", err)
  69. os.Exit(1)
  70. }
  71. defer os.RemoveAll(testDataDirName)
  72. os.Remove(filepath.Join(testDataDirName, psiphon.DATA_STORE_FILENAME))
  73. psiphon.SetEmitDiagnosticNotices(true)
  74. configJSON, err := ioutil.ReadFile("../controller_test.config")
  75. if err != nil {
  76. // Skip, don't fail, if config file is not present
  77. t.Skipf("error loading configuration file: %s", err)
  78. }
  79. // These fields must be filled in before calling LoadConfig
  80. var modifyConfig map[string]interface{}
  81. json.Unmarshal(configJSON, &modifyConfig)
  82. modifyConfig["DataStoreDirectory"] = testDataDirName
  83. modifyConfig["RemoteServerListDownloadFilename"] = filepath.Join(testDataDirName, "server_list_compressed")
  84. modifyConfig["UpgradeDownloadFilename"] = filepath.Join(testDataDirName, "upgrade")
  85. configJSON, _ = json.Marshal(modifyConfig)
  86. config, err := psiphon.LoadConfig(configJSON)
  87. if err != nil {
  88. t.Fatalf("error processing configuration file: %s", err)
  89. }
  90. postActiveTunnelTerminateDelay := 250 * time.Millisecond
  91. testDuration := 5 * time.Minute
  92. memInspectionFrequency := 10 * time.Second
  93. maxSysMemory := uint64(11 * 1024 * 1024)
  94. config.ClientVersion = "999999999"
  95. config.TunnelPoolSize = 1
  96. fetchRemoteServerListRetryPeriodSeconds := 0
  97. config.FetchRemoteServerListRetryPeriodSeconds = &fetchRemoteServerListRetryPeriodSeconds
  98. establishTunnelPausePeriodSeconds := 1
  99. config.EstablishTunnelPausePeriodSeconds = &establishTunnelPausePeriodSeconds
  100. config.TunnelProtocol = ""
  101. config.DisableLocalSocksProxy = true
  102. config.DisableLocalHTTPProxy = true
  103. config.ConnectionWorkerPoolSize = 10
  104. config.LimitMeekConnectionWorkers = 5
  105. config.LimitMeekBufferSizes = true
  106. config.StaggerConnectionWorkersMilliseconds = 100
  107. config.IgnoreHandshakeStatsRegexps = true
  108. err = psiphon.InitDataStore(config)
  109. if err != nil {
  110. t.Fatalf("error initializing datastore: %s", err)
  111. }
  112. var controller *psiphon.Controller
  113. var controllerCtx context.Context
  114. var controllerStopRunning context.CancelFunc
  115. var controllerWaitGroup *sync.WaitGroup
  116. restartController := make(chan bool, 1)
  117. reconnectTunnel := make(chan bool, 1)
  118. tunnelsEstablished := int32(0)
  119. psiphon.SetNoticeWriter(psiphon.NewNoticeReceiver(
  120. func(notice []byte) {
  121. noticeType, payload, err := psiphon.GetNotice(notice)
  122. if err != nil {
  123. return
  124. }
  125. switch noticeType {
  126. case "Tunnels":
  127. count := int(payload["count"].(float64))
  128. if count > 0 {
  129. atomic.AddInt32(&tunnelsEstablished, 1)
  130. time.Sleep(postActiveTunnelTerminateDelay)
  131. doRestartController := (testMode == testModeRestartController)
  132. if testMode == testModeReconnectAndRestart {
  133. doRestartController = common.FlipCoin()
  134. }
  135. if doRestartController {
  136. select {
  137. case restartController <- true:
  138. default:
  139. }
  140. } else {
  141. select {
  142. case reconnectTunnel <- true:
  143. default:
  144. }
  145. }
  146. }
  147. case "Info":
  148. message := payload["message"].(string)
  149. if strings.Contains(message, "peak concurrent establish tunnels") {
  150. fmt.Printf("%s, ", message)
  151. } else if strings.Contains(message, "peak concurrent meek establish tunnels") {
  152. fmt.Printf("%s\n", message)
  153. }
  154. }
  155. }))
  156. startController := func() {
  157. controller, err = psiphon.NewController(config)
  158. if err != nil {
  159. t.Fatalf("error creating controller: %s", err)
  160. }
  161. controllerCtx, controllerStopRunning = context.WithCancel(context.Background())
  162. controllerWaitGroup = new(sync.WaitGroup)
  163. controllerWaitGroup.Add(1)
  164. go func() {
  165. defer controllerWaitGroup.Done()
  166. controller.Run(controllerCtx)
  167. }()
  168. }
  169. stopController := func() {
  170. controllerStopRunning()
  171. controllerWaitGroup.Wait()
  172. }
  173. testTimer := time.NewTimer(testDuration)
  174. defer testTimer.Stop()
  175. memInspectionTicker := time.NewTicker(memInspectionFrequency)
  176. lastTunnelsEstablished := int32(0)
  177. startController()
  178. test_loop:
  179. for {
  180. select {
  181. case <-testTimer.C:
  182. break test_loop
  183. case <-memInspectionTicker.C:
  184. var m runtime.MemStats
  185. runtime.ReadMemStats(&m)
  186. if m.Sys > maxSysMemory {
  187. t.Fatalf("sys memory exceeds limit: %d", m.Sys)
  188. } else {
  189. n := atomic.LoadInt32(&tunnelsEstablished)
  190. fmt.Printf("Tunnels established: %d, MemStats.Sys (peak system memory used): %s, MemStats.TotalAlloc (cumulative allocations): %s\n",
  191. n, common.FormatByteCount(m.Sys), common.FormatByteCount(m.TotalAlloc))
  192. if lastTunnelsEstablished-n >= 0 {
  193. t.Fatalf("expected established tunnels")
  194. }
  195. lastTunnelsEstablished = n
  196. }
  197. case <-reconnectTunnel:
  198. controller.TerminateNextActiveTunnel()
  199. case <-restartController:
  200. stopController()
  201. startController()
  202. }
  203. }
  204. stopController()
  205. }