dataStoreRecovery_test.go 6.9 KB

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