github.com/shyftnetwork/go-empyrean@v1.8.3-0.20191127201940-fbfca9338f04/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/ShyftNetwork/go-empyrean/common"
    29  	"github.com/ShyftNetwork/go-empyrean/log"
    30  	"github.com/ShyftNetwork/go-empyrean/node"
    31  	"github.com/ShyftNetwork/go-empyrean/p2p/enode"
    32  	"github.com/ShyftNetwork/go-empyrean/p2p/simulations"
    33  	"github.com/ShyftNetwork/go-empyrean/p2p/simulations/adapters"
    34  	"github.com/ShyftNetwork/go-empyrean/swarm/network"
    35  	"github.com/ShyftNetwork/go-empyrean/swarm/network/simulation"
    36  	"github.com/ShyftNetwork/go-empyrean/swarm/pot"
    37  	"github.com/ShyftNetwork/go-empyrean/swarm/state"
    38  	"github.com/ShyftNetwork/go-empyrean/swarm/storage"
    39  	"github.com/ShyftNetwork/go-empyrean/swarm/storage/mock"
    40  	mockmem "github.com/ShyftNetwork/go-empyrean/swarm/storage/mock/mem"
    41  	"github.com/ShyftNetwork/go-empyrean/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": streamerFunc,
   111  }
   112  
   113  func streamerFunc(ctx *adapters.ServiceContext, bucket *sync.Map) (s node.Service, cleanup func(), err error) {
   114  	n := ctx.Config.Node()
   115  	addr := network.NewAddr(n)
   116  	store, datadir, err := createTestLocalStorageForID(n.ID(), addr)
   117  	if err != nil {
   118  		return nil, nil, err
   119  	}
   120  	bucket.Store(bucketKeyStore, store)
   121  	localStore := store.(*storage.LocalStore)
   122  	netStore, err := storage.NewNetStore(localStore, nil)
   123  	if err != nil {
   124  		return nil, nil, err
   125  	}
   126  	kad := network.NewKademlia(addr.Over(), network.NewKadParams())
   127  	delivery := NewDelivery(kad, netStore)
   128  	netStore.NewNetFetcherFunc = network.NewFetcherFactory(dummyRequestFromPeers, true).New
   129  
   130  	r := NewRegistry(addr.ID(), delivery, netStore, state.NewInmemoryStore(), &RegistryOptions{
   131  		Retrieval:       RetrievalDisabled,
   132  		Syncing:         SyncingAutoSubscribe,
   133  		SyncUpdateDelay: 3 * time.Second,
   134  	}, nil)
   135  
   136  	bucket.Store(bucketKeyRegistry, r)
   137  
   138  	cleanup = func() {
   139  		os.RemoveAll(datadir)
   140  		netStore.Close()
   141  		r.Close()
   142  	}
   143  
   144  	return r, cleanup, nil
   145  
   146  }
   147  
   148  func testSyncingViaGlobalSync(t *testing.T, chunkCount int, nodeCount int) {
   149  	sim := simulation.New(simServiceMap)
   150  	defer sim.Close()
   151  
   152  	log.Info("Initializing test config")
   153  
   154  	conf := &synctestConfig{}
   155  	//map of discover ID to indexes of chunks expected at that ID
   156  	conf.idToChunksMap = make(map[enode.ID][]int)
   157  	//map of overlay address to discover ID
   158  	conf.addrToIDMap = make(map[string]enode.ID)
   159  	//array where the generated chunk hashes will be stored
   160  	conf.hashes = make([]storage.Address, 0)
   161  
   162  	err := sim.UploadSnapshot(fmt.Sprintf("testing/snapshot_%d.json", nodeCount))
   163  	if err != nil {
   164  		t.Fatal(err)
   165  	}
   166  
   167  	ctx, cancelSimRun := context.WithTimeout(context.Background(), 2*time.Minute)
   168  	defer cancelSimRun()
   169  
   170  	if _, err := sim.WaitTillHealthy(ctx); err != nil {
   171  		t.Fatal(err)
   172  	}
   173  
   174  	disconnections := sim.PeerEvents(
   175  		context.Background(),
   176  		sim.NodeIDs(),
   177  		simulation.NewPeerEventsFilter().Drop(),
   178  	)
   179  
   180  	var disconnected atomic.Value
   181  	go func() {
   182  		for d := range disconnections {
   183  			if d.Error != nil {
   184  				log.Error("peer drop", "node", d.NodeID, "peer", d.PeerID)
   185  				disconnected.Store(true)
   186  			}
   187  		}
   188  	}()
   189  
   190  	result := runSim(conf, ctx, sim, chunkCount)
   191  
   192  	if result.Error != nil {
   193  		t.Fatal(result.Error)
   194  	}
   195  	if yes, ok := disconnected.Load().(bool); ok && yes {
   196  		t.Fatal("disconnect events received")
   197  	}
   198  	log.Info("Simulation ended")
   199  }
   200  
   201  func runSim(conf *synctestConfig, ctx context.Context, sim *simulation.Simulation, chunkCount int) simulation.Result {
   202  
   203  	return sim.Run(ctx, func(ctx context.Context, sim *simulation.Simulation) error {
   204  		nodeIDs := sim.UpNodeIDs()
   205  		for _, n := range nodeIDs {
   206  			//get the kademlia overlay address from this ID
   207  			a := n.Bytes()
   208  			//append it to the array of all overlay addresses
   209  			conf.addrs = append(conf.addrs, a)
   210  			//the proximity calculation is on overlay addr,
   211  			//the p2p/simulations check func triggers on enode.ID,
   212  			//so we need to know which overlay addr maps to which nodeID
   213  			conf.addrToIDMap[string(a)] = n
   214  		}
   215  
   216  		//get the node at that index
   217  		//this is the node selected for upload
   218  		node := sim.Net.GetRandomUpNode()
   219  		item, ok := sim.NodeItem(node.ID(), bucketKeyStore)
   220  		if !ok {
   221  			return fmt.Errorf("No localstore")
   222  		}
   223  		lstore := item.(*storage.LocalStore)
   224  		hashes, err := uploadFileToSingleNodeStore(node.ID(), chunkCount, lstore)
   225  		if err != nil {
   226  			return err
   227  		}
   228  		for _, h := range hashes {
   229  			evt := &simulations.Event{
   230  				Type: EventTypeChunkCreated,
   231  				Node: sim.Net.GetNode(node.ID()),
   232  				Data: h.String(),
   233  			}
   234  			sim.Net.Events().Send(evt)
   235  		}
   236  		conf.hashes = append(conf.hashes, hashes...)
   237  		mapKeysToNodes(conf)
   238  
   239  		// File retrieval check is repeated until all uploaded files are retrieved from all nodes
   240  		// or until the timeout is reached.
   241  		var globalStore mock.GlobalStorer
   242  		if *useMockStore {
   243  			globalStore = mockmem.NewGlobalStore()
   244  		}
   245  	REPEAT:
   246  		for {
   247  			for _, id := range nodeIDs {
   248  				//for each expected chunk, check if it is in the local store
   249  				localChunks := conf.idToChunksMap[id]
   250  				for _, ch := range localChunks {
   251  					//get the real chunk by the index in the index array
   252  					chunk := conf.hashes[ch]
   253  					log.Trace(fmt.Sprintf("node has chunk: %s:", chunk))
   254  					//check if the expected chunk is indeed in the localstore
   255  					var err error
   256  					if *useMockStore {
   257  						//use the globalStore if the mockStore should be used; in that case,
   258  						//the complete localStore stack is bypassed for getting the chunk
   259  						_, err = globalStore.Get(common.BytesToAddress(id.Bytes()), chunk)
   260  					} else {
   261  						//use the actual localstore
   262  						item, ok := sim.NodeItem(id, bucketKeyStore)
   263  						if !ok {
   264  							return fmt.Errorf("Error accessing localstore")
   265  						}
   266  						lstore := item.(*storage.LocalStore)
   267  						_, err = lstore.Get(ctx, chunk)
   268  					}
   269  					if err != nil {
   270  						log.Debug(fmt.Sprintf("Chunk %s NOT found for id %s", chunk, id))
   271  						// Do not get crazy with logging the warn message
   272  						time.Sleep(500 * time.Millisecond)
   273  						continue REPEAT
   274  					}
   275  					evt := &simulations.Event{
   276  						Type: EventTypeChunkArrived,
   277  						Node: sim.Net.GetNode(id),
   278  						Data: chunk.String(),
   279  					}
   280  					sim.Net.Events().Send(evt)
   281  					log.Debug(fmt.Sprintf("Chunk %s IS FOUND for id %s", chunk, id))
   282  				}
   283  			}
   284  			return nil
   285  		}
   286  	})
   287  }
   288  
   289  //map chunk keys to addresses which are responsible
   290  func mapKeysToNodes(conf *synctestConfig) {
   291  	nodemap := make(map[string][]int)
   292  	//build a pot for chunk hashes
   293  	np := pot.NewPot(nil, 0)
   294  	indexmap := make(map[string]int)
   295  	for i, a := range conf.addrs {
   296  		indexmap[string(a)] = i
   297  		np, _, _ = pot.Add(np, a, pof)
   298  	}
   299  
   300  	ppmap := network.NewPeerPotMap(network.NewKadParams().NeighbourhoodSize, conf.addrs)
   301  
   302  	//for each address, run EachNeighbour on the chunk hashes pot to identify closest nodes
   303  	log.Trace(fmt.Sprintf("Generated hash chunk(s): %v", conf.hashes))
   304  	for i := 0; i < len(conf.hashes); i++ {
   305  		var a []byte
   306  		np.EachNeighbour([]byte(conf.hashes[i]), pof, func(val pot.Val, po int) bool {
   307  			// take the first address
   308  			a = val.([]byte)
   309  			return false
   310  		})
   311  
   312  		nns := ppmap[common.Bytes2Hex(a)].NNSet
   313  		nns = append(nns, a)
   314  
   315  		for _, p := range nns {
   316  			nodemap[string(p)] = append(nodemap[string(p)], i)
   317  		}
   318  	}
   319  	for addr, chunks := range nodemap {
   320  		//this selects which chunks are expected to be found with the given node
   321  		conf.idToChunksMap[conf.addrToIDMap[addr]] = chunks
   322  	}
   323  	log.Debug(fmt.Sprintf("Map of expected chunks by ID: %v", conf.idToChunksMap))
   324  }
   325  
   326  //upload a file(chunks) to a single local node store
   327  func uploadFileToSingleNodeStore(id enode.ID, chunkCount int, lstore *storage.LocalStore) ([]storage.Address, error) {
   328  	log.Debug(fmt.Sprintf("Uploading to node id: %s", id))
   329  	fileStore := storage.NewFileStore(lstore, storage.NewFileStoreParams())
   330  	size := chunkSize
   331  	var rootAddrs []storage.Address
   332  	for i := 0; i < chunkCount; i++ {
   333  		rk, wait, err := fileStore.Store(context.TODO(), testutil.RandomReader(i, size), int64(size), false)
   334  		if err != nil {
   335  			return nil, err
   336  		}
   337  		err = wait(context.TODO())
   338  		if err != nil {
   339  			return nil, err
   340  		}
   341  		rootAddrs = append(rootAddrs, (rk))
   342  	}
   343  
   344  	return rootAddrs, nil
   345  }