syncer_test.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package stream
  17. import (
  18. "context"
  19. crand "crypto/rand"
  20. "fmt"
  21. "io"
  22. "io/ioutil"
  23. "math"
  24. "sync"
  25. "testing"
  26. "time"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/p2p/discover"
  29. "github.com/ethereum/go-ethereum/p2p/simulations"
  30. "github.com/ethereum/go-ethereum/rpc"
  31. "github.com/ethereum/go-ethereum/swarm/log"
  32. "github.com/ethereum/go-ethereum/swarm/network"
  33. streamTesting "github.com/ethereum/go-ethereum/swarm/network/stream/testing"
  34. "github.com/ethereum/go-ethereum/swarm/storage"
  35. )
  36. const dataChunkCount = 200
  37. func TestSyncerSimulation(t *testing.T) {
  38. testSyncBetweenNodes(t, 2, 1, dataChunkCount, true, 1)
  39. testSyncBetweenNodes(t, 4, 1, dataChunkCount, true, 1)
  40. testSyncBetweenNodes(t, 8, 1, dataChunkCount, true, 1)
  41. testSyncBetweenNodes(t, 16, 1, dataChunkCount, true, 1)
  42. }
  43. func createMockStore(id discover.NodeID, addr *network.BzzAddr) (storage.ChunkStore, error) {
  44. var err error
  45. address := common.BytesToAddress(id.Bytes())
  46. mockStore := globalStore.NewNodeStore(address)
  47. params := storage.NewDefaultLocalStoreParams()
  48. datadirs[id], err = ioutil.TempDir("", "localMockStore-"+id.TerminalString())
  49. if err != nil {
  50. return nil, err
  51. }
  52. params.Init(datadirs[id])
  53. params.BaseKey = addr.Over()
  54. lstore, err := storage.NewLocalStore(params, mockStore)
  55. return lstore, nil
  56. }
  57. func testSyncBetweenNodes(t *testing.T, nodes, conns, chunkCount int, skipCheck bool, po uint8) {
  58. defer setDefaultSkipCheck(defaultSkipCheck)
  59. defaultSkipCheck = skipCheck
  60. //data directories for each node and store
  61. datadirs = make(map[discover.NodeID]string)
  62. if *useMockStore {
  63. createStoreFunc = createMockStore
  64. createGlobalStore()
  65. } else {
  66. createStoreFunc = createTestLocalStorageFromSim
  67. }
  68. defer datadirsCleanup()
  69. registries = make(map[discover.NodeID]*TestRegistry)
  70. toAddr = func(id discover.NodeID) *network.BzzAddr {
  71. addr := network.NewAddrFromNodeID(id)
  72. //hack to put addresses in same space
  73. addr.OAddr[0] = byte(0)
  74. return addr
  75. }
  76. conf := &streamTesting.RunConfig{
  77. Adapter: *adapter,
  78. NodeCount: nodes,
  79. ConnLevel: conns,
  80. ToAddr: toAddr,
  81. Services: services,
  82. EnableMsgEvents: false,
  83. }
  84. // HACK: these are global variables in the test so that they are available for
  85. // the service constructor function
  86. // TODO: will this work with exec/docker adapter?
  87. // localstore of nodes made available for action and check calls
  88. stores = make(map[discover.NodeID]storage.ChunkStore)
  89. deliveries = make(map[discover.NodeID]*Delivery)
  90. // create context for simulation run
  91. timeout := 30 * time.Second
  92. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  93. // defer cancel should come before defer simulation teardown
  94. defer cancel()
  95. // create simulation network with the config
  96. sim, teardown, err := streamTesting.NewSimulation(conf)
  97. var rpcSubscriptionsWg sync.WaitGroup
  98. defer func() {
  99. rpcSubscriptionsWg.Wait()
  100. teardown()
  101. }()
  102. if err != nil {
  103. t.Fatal(err.Error())
  104. }
  105. nodeIndex := make(map[discover.NodeID]int)
  106. for i, id := range sim.IDs {
  107. nodeIndex[id] = i
  108. if !*useMockStore {
  109. stores[id] = sim.Stores[i]
  110. sim.Stores[i] = stores[id]
  111. }
  112. }
  113. // peerCount function gives the number of peer connections for a nodeID
  114. // this is needed for the service run function to wait until
  115. // each protocol instance runs and the streamer peers are available
  116. peerCount = func(id discover.NodeID) int {
  117. if sim.IDs[0] == id || sim.IDs[nodes-1] == id {
  118. return 1
  119. }
  120. return 2
  121. }
  122. waitPeerErrC = make(chan error)
  123. // create DBAPI-s for all nodes
  124. dbs := make([]*storage.DBAPI, nodes)
  125. for i := 0; i < nodes; i++ {
  126. dbs[i] = storage.NewDBAPI(sim.Stores[i].(*storage.LocalStore))
  127. }
  128. // collect hashes in po 1 bin for each node
  129. hashes := make([][]storage.Address, nodes)
  130. totalHashes := 0
  131. hashCounts := make([]int, nodes)
  132. for i := nodes - 1; i >= 0; i-- {
  133. if i < nodes-1 {
  134. hashCounts[i] = hashCounts[i+1]
  135. }
  136. dbs[i].Iterator(0, math.MaxUint64, po, func(addr storage.Address, index uint64) bool {
  137. hashes[i] = append(hashes[i], addr)
  138. totalHashes++
  139. hashCounts[i]++
  140. return true
  141. })
  142. }
  143. // errc is error channel for simulation
  144. errc := make(chan error, 1)
  145. quitC := make(chan struct{})
  146. defer close(quitC)
  147. // action is subscribe
  148. action := func(ctx context.Context) error {
  149. // need to wait till an aynchronous process registers the peers in streamer.peers
  150. // that is used by Subscribe
  151. // the global peerCount function tells how many connections each node has
  152. // TODO: this is to be reimplemented with peerEvent watcher without global var
  153. i := 0
  154. for err := range waitPeerErrC {
  155. if err != nil {
  156. return fmt.Errorf("error waiting for peers: %s", err)
  157. }
  158. i++
  159. if i == nodes {
  160. break
  161. }
  162. }
  163. // each node Subscribes to each other's swarmChunkServerStreamName
  164. for j := 0; j < nodes-1; j++ {
  165. id := sim.IDs[j]
  166. sim.Stores[j] = stores[id]
  167. err := sim.CallClient(id, func(client *rpc.Client) error {
  168. // report disconnect events to the error channel cos peers should not disconnect
  169. doneC, err := streamTesting.WatchDisconnections(id, client, errc, quitC)
  170. if err != nil {
  171. return err
  172. }
  173. rpcSubscriptionsWg.Add(1)
  174. go func() {
  175. <-doneC
  176. rpcSubscriptionsWg.Done()
  177. }()
  178. ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
  179. defer cancel()
  180. // start syncing, i.e., subscribe to upstream peers po 1 bin
  181. sid := sim.IDs[j+1]
  182. return client.CallContext(ctx, nil, "stream_subscribeStream", sid, NewStream("SYNC", FormatSyncBinKey(1), false), NewRange(0, 0), Top)
  183. })
  184. if err != nil {
  185. return err
  186. }
  187. }
  188. // here we distribute chunks of a random file into stores 1...nodes
  189. rrFileStore := storage.NewFileStore(newRoundRobinStore(sim.Stores[1:]...), storage.NewFileStoreParams())
  190. size := chunkCount * chunkSize
  191. _, wait, err := rrFileStore.Store(ctx, io.LimitReader(crand.Reader, int64(size)), int64(size), false)
  192. if err != nil {
  193. t.Fatal(err.Error())
  194. }
  195. // need to wait cos we then immediately collect the relevant bin content
  196. wait(ctx)
  197. if err != nil {
  198. t.Fatal(err.Error())
  199. }
  200. return nil
  201. }
  202. // this makes sure check is not called before the previous call finishes
  203. check := func(ctx context.Context, id discover.NodeID) (bool, error) {
  204. select {
  205. case err := <-errc:
  206. return false, err
  207. case <-ctx.Done():
  208. return false, ctx.Err()
  209. default:
  210. }
  211. i := nodeIndex[id]
  212. var total, found int
  213. for j := i; j < nodes; j++ {
  214. total += len(hashes[j])
  215. for _, key := range hashes[j] {
  216. chunk, err := dbs[i].Get(key)
  217. if err == storage.ErrFetching {
  218. <-chunk.ReqC
  219. } else if err != nil {
  220. continue
  221. }
  222. // needed for leveldb not to be closed?
  223. // chunk.WaitToStore()
  224. found++
  225. }
  226. }
  227. log.Debug("sync check", "node", id, "index", i, "bin", po, "found", found, "total", total)
  228. return total == found, nil
  229. }
  230. conf.Step = &simulations.Step{
  231. Action: action,
  232. Trigger: streamTesting.Trigger(500*time.Millisecond, quitC, sim.IDs[0:nodes-1]...),
  233. Expect: &simulations.Expectation{
  234. Nodes: sim.IDs[0:1],
  235. Check: check,
  236. },
  237. }
  238. startedAt := time.Now()
  239. result, err := sim.Run(ctx, conf)
  240. finishedAt := time.Now()
  241. if err != nil {
  242. t.Fatalf("Setting up simulation failed: %v", err)
  243. }
  244. if result.Error != nil {
  245. t.Fatalf("Simulation failed: %s", result.Error)
  246. }
  247. streamTesting.CheckResult(t, result, startedAt, finishedAt)
  248. }