snapshot_sync_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. "errors"
  20. "fmt"
  21. "os"
  22. "runtime"
  23. "sync"
  24. "testing"
  25. "time"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/log"
  28. "github.com/ethereum/go-ethereum/node"
  29. "github.com/ethereum/go-ethereum/p2p/enode"
  30. "github.com/ethereum/go-ethereum/p2p/simulations"
  31. "github.com/ethereum/go-ethereum/p2p/simulations/adapters"
  32. "github.com/ethereum/go-ethereum/swarm/chunk"
  33. "github.com/ethereum/go-ethereum/swarm/network"
  34. "github.com/ethereum/go-ethereum/swarm/network/simulation"
  35. "github.com/ethereum/go-ethereum/swarm/pot"
  36. "github.com/ethereum/go-ethereum/swarm/state"
  37. "github.com/ethereum/go-ethereum/swarm/storage"
  38. "github.com/ethereum/go-ethereum/swarm/storage/mock"
  39. mockmem "github.com/ethereum/go-ethereum/swarm/storage/mock/mem"
  40. "github.com/ethereum/go-ethereum/swarm/testutil"
  41. )
  42. type synctestConfig struct {
  43. addrs [][]byte
  44. hashes []storage.Address
  45. idToChunksMap map[enode.ID][]int
  46. //chunksToNodesMap map[string][]int
  47. addrToIDMap map[string]enode.ID
  48. }
  49. const (
  50. // EventTypeNode is the type of event emitted when a node is either
  51. // created, started or stopped
  52. EventTypeChunkCreated simulations.EventType = "chunkCreated"
  53. EventTypeChunkOffered simulations.EventType = "chunkOffered"
  54. EventTypeChunkWanted simulations.EventType = "chunkWanted"
  55. EventTypeChunkDelivered simulations.EventType = "chunkDelivered"
  56. EventTypeChunkArrived simulations.EventType = "chunkArrived"
  57. EventTypeSimTerminated simulations.EventType = "simTerminated"
  58. )
  59. // Tests in this file should not request chunks from peers.
  60. // This function will panic indicating that there is a problem if request has been made.
  61. func dummyRequestFromPeers(_ context.Context, req *network.Request) (*enode.ID, chan struct{}, error) {
  62. panic(fmt.Sprintf("unexpected request: address %s, source %s", req.Addr.String(), req.Source.String()))
  63. }
  64. //This test is a syncing test for nodes.
  65. //One node is randomly selected to be the pivot node.
  66. //A configurable number of chunks and nodes can be
  67. //provided to the test, the number of chunks is uploaded
  68. //to the pivot node, and we check that nodes get the chunks
  69. //they are expected to store based on the syncing protocol.
  70. //Number of chunks and nodes can be provided via commandline too.
  71. func TestSyncingViaGlobalSync(t *testing.T) {
  72. if runtime.GOOS == "darwin" && os.Getenv("TRAVIS") == "true" {
  73. t.Skip("Flaky on mac on travis")
  74. }
  75. if testutil.RaceEnabled {
  76. t.Skip("Segfaults on Travis with -race")
  77. }
  78. //if nodes/chunks have been provided via commandline,
  79. //run the tests with these values
  80. if *nodes != 0 && *chunks != 0 {
  81. log.Info(fmt.Sprintf("Running test with %d chunks and %d nodes...", *chunks, *nodes))
  82. testSyncingViaGlobalSync(t, *chunks, *nodes)
  83. } else {
  84. chunkCounts := []int{4, 32}
  85. nodeCounts := []int{32, 16}
  86. //if the `longrunning` flag has been provided
  87. //run more test combinations
  88. if *longrunning {
  89. chunkCounts = []int{64, 128}
  90. nodeCounts = []int{32, 64}
  91. }
  92. for _, chunkCount := range chunkCounts {
  93. for _, n := range nodeCounts {
  94. log.Info(fmt.Sprintf("Long running test with %d chunks and %d nodes...", chunkCount, n))
  95. testSyncingViaGlobalSync(t, chunkCount, n)
  96. }
  97. }
  98. }
  99. }
  100. var simServiceMap = map[string]simulation.ServiceFunc{
  101. "streamer": func(ctx *adapters.ServiceContext, bucket *sync.Map) (s node.Service, cleanup func(), err error) {
  102. addr, netStore, delivery, clean, err := newNetStoreAndDeliveryWithRequestFunc(ctx, bucket, dummyRequestFromPeers)
  103. if err != nil {
  104. return nil, nil, err
  105. }
  106. store := state.NewInmemoryStore()
  107. r := NewRegistry(addr.ID(), delivery, netStore, store, &RegistryOptions{
  108. Syncing: SyncingAutoSubscribe,
  109. SyncUpdateDelay: 3 * time.Second,
  110. }, nil)
  111. bucket.Store(bucketKeyRegistry, r)
  112. cleanup = func() {
  113. r.Close()
  114. clean()
  115. }
  116. return r, cleanup, nil
  117. },
  118. }
  119. func testSyncingViaGlobalSync(t *testing.T, chunkCount int, nodeCount int) {
  120. sim := simulation.New(simServiceMap)
  121. defer sim.Close()
  122. log.Info("Initializing test config")
  123. conf := &synctestConfig{}
  124. //map of discover ID to indexes of chunks expected at that ID
  125. conf.idToChunksMap = make(map[enode.ID][]int)
  126. //map of overlay address to discover ID
  127. conf.addrToIDMap = make(map[string]enode.ID)
  128. //array where the generated chunk hashes will be stored
  129. conf.hashes = make([]storage.Address, 0)
  130. ctx, cancelSimRun := context.WithTimeout(context.Background(), 3*time.Minute)
  131. defer cancelSimRun()
  132. filename := fmt.Sprintf("testing/snapshot_%d.json", nodeCount)
  133. err := sim.UploadSnapshot(ctx, filename)
  134. if err != nil {
  135. t.Fatal(err)
  136. }
  137. result := runSim(conf, ctx, sim, chunkCount)
  138. if result.Error != nil {
  139. t.Fatal(result.Error)
  140. }
  141. log.Info("Simulation ended")
  142. }
  143. func runSim(conf *synctestConfig, ctx context.Context, sim *simulation.Simulation, chunkCount int) simulation.Result {
  144. return sim.Run(ctx, func(ctx context.Context, sim *simulation.Simulation) (err error) {
  145. disconnected := watchDisconnections(ctx, sim)
  146. defer func() {
  147. if err != nil && disconnected.bool() {
  148. err = errors.New("disconnect events received")
  149. }
  150. }()
  151. nodeIDs := sim.UpNodeIDs()
  152. for _, n := range nodeIDs {
  153. //get the kademlia overlay address from this ID
  154. a := n.Bytes()
  155. //append it to the array of all overlay addresses
  156. conf.addrs = append(conf.addrs, a)
  157. //the proximity calculation is on overlay addr,
  158. //the p2p/simulations check func triggers on enode.ID,
  159. //so we need to know which overlay addr maps to which nodeID
  160. conf.addrToIDMap[string(a)] = n
  161. }
  162. //get the node at that index
  163. //this is the node selected for upload
  164. node := sim.Net.GetRandomUpNode()
  165. item, ok := sim.NodeItem(node.ID(), bucketKeyStore)
  166. if !ok {
  167. return errors.New("no store in simulation bucket")
  168. }
  169. store := item.(chunk.Store)
  170. hashes, err := uploadFileToSingleNodeStore(node.ID(), chunkCount, store)
  171. if err != nil {
  172. return err
  173. }
  174. for _, h := range hashes {
  175. evt := &simulations.Event{
  176. Type: EventTypeChunkCreated,
  177. Node: sim.Net.GetNode(node.ID()),
  178. Data: h.String(),
  179. }
  180. sim.Net.Events().Send(evt)
  181. }
  182. conf.hashes = append(conf.hashes, hashes...)
  183. mapKeysToNodes(conf)
  184. // File retrieval check is repeated until all uploaded files are retrieved from all nodes
  185. // or until the timeout is reached.
  186. var globalStore mock.GlobalStorer
  187. if *useMockStore {
  188. globalStore = mockmem.NewGlobalStore()
  189. }
  190. REPEAT:
  191. for {
  192. for _, id := range nodeIDs {
  193. //for each expected chunk, check if it is in the local store
  194. localChunks := conf.idToChunksMap[id]
  195. for _, ch := range localChunks {
  196. //get the real chunk by the index in the index array
  197. ch := conf.hashes[ch]
  198. log.Trace("node has chunk", "address", ch)
  199. //check if the expected chunk is indeed in the localstore
  200. var err error
  201. if *useMockStore {
  202. //use the globalStore if the mockStore should be used; in that case,
  203. //the complete localStore stack is bypassed for getting the chunk
  204. _, err = globalStore.Get(common.BytesToAddress(id.Bytes()), ch)
  205. } else {
  206. //use the actual localstore
  207. item, ok := sim.NodeItem(id, bucketKeyStore)
  208. if !ok {
  209. return errors.New("no store in simulation bucket")
  210. }
  211. store := item.(chunk.Store)
  212. _, err = store.Get(ctx, chunk.ModeGetLookup, ch)
  213. }
  214. if err != nil {
  215. log.Debug("chunk not found", "address", ch.Hex(), "node", id)
  216. // Do not get crazy with logging the warn message
  217. time.Sleep(500 * time.Millisecond)
  218. continue REPEAT
  219. }
  220. evt := &simulations.Event{
  221. Type: EventTypeChunkArrived,
  222. Node: sim.Net.GetNode(id),
  223. Data: ch.String(),
  224. }
  225. sim.Net.Events().Send(evt)
  226. log.Trace("chunk found", "address", ch.Hex(), "node", id)
  227. }
  228. }
  229. return nil
  230. }
  231. })
  232. }
  233. //map chunk keys to addresses which are responsible
  234. func mapKeysToNodes(conf *synctestConfig) {
  235. nodemap := make(map[string][]int)
  236. //build a pot for chunk hashes
  237. np := pot.NewPot(nil, 0)
  238. indexmap := make(map[string]int)
  239. for i, a := range conf.addrs {
  240. indexmap[string(a)] = i
  241. np, _, _ = pot.Add(np, a, pof)
  242. }
  243. ppmap := network.NewPeerPotMap(network.NewKadParams().NeighbourhoodSize, conf.addrs)
  244. //for each address, run EachNeighbour on the chunk hashes pot to identify closest nodes
  245. log.Trace(fmt.Sprintf("Generated hash chunk(s): %v", conf.hashes))
  246. for i := 0; i < len(conf.hashes); i++ {
  247. var a []byte
  248. np.EachNeighbour([]byte(conf.hashes[i]), pof, func(val pot.Val, po int) bool {
  249. // take the first address
  250. a = val.([]byte)
  251. return false
  252. })
  253. nns := ppmap[common.Bytes2Hex(a)].NNSet
  254. nns = append(nns, a)
  255. for _, p := range nns {
  256. nodemap[string(p)] = append(nodemap[string(p)], i)
  257. }
  258. }
  259. for addr, chunks := range nodemap {
  260. //this selects which chunks are expected to be found with the given node
  261. conf.idToChunksMap[conf.addrToIDMap[addr]] = chunks
  262. }
  263. log.Debug(fmt.Sprintf("Map of expected chunks by ID: %v", conf.idToChunksMap))
  264. }
  265. //upload a file(chunks) to a single local node store
  266. func uploadFileToSingleNodeStore(id enode.ID, chunkCount int, store chunk.Store) ([]storage.Address, error) {
  267. log.Debug(fmt.Sprintf("Uploading to node id: %s", id))
  268. fileStore := storage.NewFileStore(store, storage.NewFileStoreParams(), chunk.NewTags())
  269. size := chunkSize
  270. var rootAddrs []storage.Address
  271. for i := 0; i < chunkCount; i++ {
  272. rk, wait, err := fileStore.Store(context.TODO(), testutil.RandomReader(i, size), int64(size), false)
  273. if err != nil {
  274. return nil, err
  275. }
  276. err = wait(context.TODO())
  277. if err != nil {
  278. return nil, err
  279. }
  280. rootAddrs = append(rootAddrs, (rk))
  281. }
  282. return rootAddrs, nil
  283. }