dataStoreRecovery_test.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. //go:build !PSIPHON_USE_BADGER_DB && !PSIPHON_USE_FILES_DB
  2. // +build !PSIPHON_USE_BADGER_DB,!PSIPHON_USE_FILES_DB
  3. /*
  4. * Copyright (c) 2019, Psiphon Inc.
  5. * All rights reserved.
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. */
  21. package psiphon
  22. import (
  23. "context"
  24. "fmt"
  25. "io/ioutil"
  26. "os"
  27. "path/filepath"
  28. "strings"
  29. "sync"
  30. "testing"
  31. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  32. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  34. )
  35. // Set canTruncateOpenDataStore to false on platforms, such as Windows, where
  36. // the OS doesn't allow an open memory-mapped file to be truncated. This will
  37. // skip the associated test cases.
  38. var canTruncateOpenDataStore = true
  39. func TestBoltResiliency(t *testing.T) {
  40. testDataDirName, err := ioutil.TempDir("", "psiphon-bolt-recovery-test")
  41. if err != nil {
  42. t.Fatalf("TempDir failed: %s", err)
  43. }
  44. defer os.RemoveAll(testDataDirName)
  45. SetEmitDiagnosticNotices(true, true)
  46. clientConfigJSON := `
  47. {
  48. "ClientPlatform" : "",
  49. "ClientVersion" : "0000000000000000",
  50. "SponsorId" : "0000000000000000",
  51. "PropagationChannelId" : "0",
  52. "ConnectionWorkerPoolSize" : 10,
  53. "EstablishTunnelTimeoutSeconds" : 1,
  54. "EstablishTunnelPausePeriodSeconds" : 1
  55. }`
  56. clientConfig, err := LoadConfig([]byte(clientConfigJSON))
  57. if err != nil {
  58. t.Fatalf("LoadConfig failed: %s", err)
  59. }
  60. clientConfig.DataRootDirectory = testDataDirName
  61. err = clientConfig.Commit(false)
  62. if err != nil {
  63. t.Fatalf("Commit failed: %s", err)
  64. }
  65. serverEntryCount := 100
  66. noticeCandidateServers := make(chan struct{}, 1)
  67. noticeExiting := make(chan struct{}, 1)
  68. noticeResetDatastore := make(chan struct{}, 1)
  69. noticeDatastoreFailed := make(chan struct{}, 1)
  70. SetNoticeWriter(NewNoticeReceiver(
  71. func(notice []byte) {
  72. noticeType, payload, err := GetNotice(notice)
  73. if err != nil {
  74. return
  75. }
  76. printNotice := false
  77. switch noticeType {
  78. case "CandidateServers":
  79. count := int(payload["count"].(float64))
  80. if count != serverEntryCount {
  81. t.Fatalf("unexpected server entry count: %d", count)
  82. }
  83. select {
  84. case noticeCandidateServers <- struct{}{}:
  85. default:
  86. }
  87. case "Exiting":
  88. select {
  89. case noticeExiting <- struct{}{}:
  90. default:
  91. }
  92. case "Alert":
  93. message := payload["message"].(string)
  94. var channel chan struct{}
  95. if strings.Contains(message, "tryDatastoreOpenDB: reset") {
  96. channel = noticeResetDatastore
  97. } else if strings.Contains(message, "datastore has failed") {
  98. channel = noticeDatastoreFailed
  99. }
  100. if channel != nil {
  101. select {
  102. case channel <- struct{}{}:
  103. default:
  104. }
  105. }
  106. }
  107. if printNotice {
  108. fmt.Printf("%s\n", string(notice))
  109. }
  110. }))
  111. drainNoticeChannel := func(channel chan struct{}) {
  112. for {
  113. select {
  114. case channel <- struct{}{}:
  115. default:
  116. return
  117. }
  118. }
  119. }
  120. drainNoticeChannels := func() {
  121. drainNoticeChannel(noticeCandidateServers)
  122. drainNoticeChannel(noticeExiting)
  123. drainNoticeChannel(noticeResetDatastore)
  124. drainNoticeChannel(noticeDatastoreFailed)
  125. }
  126. // Paving sufficient server entries, then truncating the datastore file to
  127. // remove some server entry data, then iterating over all server entries (to
  128. // produce the CandidateServers output) triggers datastore corruption
  129. // detection and, at start up, reset/recovery.
  130. paveServerEntries := func() {
  131. for i := 0; i < serverEntryCount; i++ {
  132. n := 16
  133. fields := make(protocol.ServerEntryFields)
  134. fields["ipAddress"] = fmt.Sprintf("127.0.0.%d", i+1)
  135. fields["sshPort"] = 2222
  136. fields["sshUsername"] = prng.HexString(n)
  137. fields["sshPassword"] = prng.HexString(n)
  138. fields["sshHostKey"] = prng.HexString(n)
  139. fields["capabilities"] = []string{"SSH", "ssh-api-requests"}
  140. fields["region"] = "US"
  141. fields["configurationVersion"] = 1
  142. fields.SetLocalSource(protocol.SERVER_ENTRY_SOURCE_EMBEDDED)
  143. fields.SetLocalTimestamp(
  144. common.TruncateTimestampToHour(common.GetCurrentTimestamp()))
  145. err = StoreServerEntry(fields, true)
  146. if err != nil {
  147. t.Fatalf("StoreServerEntry failed: %s", err)
  148. }
  149. }
  150. }
  151. startController := func() func() {
  152. controller, err := NewController(clientConfig)
  153. if err != nil {
  154. t.Fatalf("NewController failed: %s", err)
  155. }
  156. ctx, cancelFunc := context.WithCancel(context.Background())
  157. controllerWaitGroup := new(sync.WaitGroup)
  158. controllerWaitGroup.Add(1)
  159. go func() {
  160. defer controllerWaitGroup.Done()
  161. controller.Run(ctx)
  162. }()
  163. return func() {
  164. cancelFunc()
  165. controllerWaitGroup.Wait()
  166. }
  167. }
  168. truncateDataStore := func() {
  169. filename := filepath.Join(testDataDirName, "ca.psiphon.PsiphonTunnel.tunnel-core", "datastore", "psiphon.boltdb")
  170. file, err := os.OpenFile(filename, os.O_RDWR, 0666)
  171. if err != nil {
  172. t.Fatalf("OpenFile failed: %s", err)
  173. }
  174. defer file.Close()
  175. fileInfo, err := file.Stat()
  176. if err != nil {
  177. t.Fatalf("Stat failed: %s", err)
  178. }
  179. err = file.Truncate(fileInfo.Size() / 4)
  180. if err != nil {
  181. t.Fatalf("Truncate failed: %s", err)
  182. }
  183. err = file.Sync()
  184. if err != nil {
  185. t.Fatalf("Sync failed: %s", err)
  186. }
  187. }
  188. // Populate datastore with 100 server entries.
  189. err = OpenDataStore(clientConfig)
  190. if err != nil {
  191. t.Fatalf("OpenDataStore failed: %s", err)
  192. }
  193. paveServerEntries()
  194. stopController := startController()
  195. <-noticeCandidateServers
  196. stopController()
  197. CloseDataStore()
  198. drainNoticeChannels()
  199. // Truncate datastore file before running controller; expect a datastore
  200. // "reset" notice on OpenDataStore.
  201. t.Logf("test: recover from datastore corrupted before opening")
  202. truncateDataStore()
  203. err = OpenDataStore(clientConfig)
  204. if err != nil {
  205. t.Fatalf("OpenDataStore failed: %s", err)
  206. }
  207. <-noticeResetDatastore
  208. if !canTruncateOpenDataStore {
  209. CloseDataStore()
  210. return
  211. }
  212. paveServerEntries()
  213. // Truncate datastore while running the controller. First, complete one
  214. // successful data scan (CandidateServers). The next scan should trigger a
  215. // datastore "failed" notice.
  216. t.Logf("test: detect corrupt datastore while running")
  217. stopController = startController()
  218. <-noticeCandidateServers
  219. truncateDataStore()
  220. <-noticeDatastoreFailed
  221. <-noticeExiting
  222. stopController()
  223. CloseDataStore()
  224. drainNoticeChannels()
  225. // Restart successfully after previous failure shutdown.
  226. t.Logf("test: after restart, recover from datastore corrupted while running")
  227. err = OpenDataStore(clientConfig)
  228. if err != nil {
  229. t.Fatalf("OpenDataStore failed: %s", err)
  230. }
  231. <-noticeResetDatastore
  232. paveServerEntries()
  233. stopController = startController()
  234. <-noticeCandidateServers
  235. stopController()
  236. CloseDataStore()
  237. }