github.com/letterj/go-ethereum@v1.8.22-0.20190204142846-520024dfd689/swarm/network/stream/snapshot_sync_test.go (about)

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