github.com/shyftnetwork/go-empyrean@v1.8.3-0.20191127201940-fbfca9338f04/swarm/network/stream/delivery.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  
    17  package stream
    18  
    19  import (
    20  	"context"
    21  	"errors"
    22  	"fmt"
    23  
    24  	"github.com/ShyftNetwork/go-empyrean/metrics"
    25  	"github.com/ShyftNetwork/go-empyrean/p2p/enode"
    26  	"github.com/ShyftNetwork/go-empyrean/swarm/log"
    27  	"github.com/ShyftNetwork/go-empyrean/swarm/network"
    28  	"github.com/ShyftNetwork/go-empyrean/swarm/spancontext"
    29  	"github.com/ShyftNetwork/go-empyrean/swarm/storage"
    30  	opentracing "github.com/opentracing/opentracing-go"
    31  )
    32  
    33  const (
    34  	swarmChunkServerStreamName = "RETRIEVE_REQUEST"
    35  	deliveryCap                = 32
    36  )
    37  
    38  var (
    39  	processReceivedChunksCount    = metrics.NewRegisteredCounter("network.stream.received_chunks.count", nil)
    40  	handleRetrieveRequestMsgCount = metrics.NewRegisteredCounter("network.stream.handle_retrieve_request_msg.count", nil)
    41  	retrieveChunkFail             = metrics.NewRegisteredCounter("network.stream.retrieve_chunks_fail.count", nil)
    42  
    43  	requestFromPeersCount     = metrics.NewRegisteredCounter("network.stream.request_from_peers.count", nil)
    44  	requestFromPeersEachCount = metrics.NewRegisteredCounter("network.stream.request_from_peers_each.count", nil)
    45  )
    46  
    47  type Delivery struct {
    48  	chunkStore storage.SyncChunkStore
    49  	kad        *network.Kademlia
    50  	getPeer    func(enode.ID) *Peer
    51  }
    52  
    53  func NewDelivery(kad *network.Kademlia, chunkStore storage.SyncChunkStore) *Delivery {
    54  	return &Delivery{
    55  		chunkStore: chunkStore,
    56  		kad:        kad,
    57  	}
    58  }
    59  
    60  // SwarmChunkServer implements Server
    61  type SwarmChunkServer struct {
    62  	deliveryC  chan []byte
    63  	batchC     chan []byte
    64  	chunkStore storage.ChunkStore
    65  	currentLen uint64
    66  	quit       chan struct{}
    67  }
    68  
    69  // NewSwarmChunkServer is SwarmChunkServer constructor
    70  func NewSwarmChunkServer(chunkStore storage.ChunkStore) *SwarmChunkServer {
    71  	s := &SwarmChunkServer{
    72  		deliveryC:  make(chan []byte, deliveryCap),
    73  		batchC:     make(chan []byte),
    74  		chunkStore: chunkStore,
    75  		quit:       make(chan struct{}),
    76  	}
    77  	go s.processDeliveries()
    78  	return s
    79  }
    80  
    81  // processDeliveries handles delivered chunk hashes
    82  func (s *SwarmChunkServer) processDeliveries() {
    83  	var hashes []byte
    84  	var batchC chan []byte
    85  	for {
    86  		select {
    87  		case <-s.quit:
    88  			return
    89  		case hash := <-s.deliveryC:
    90  			hashes = append(hashes, hash...)
    91  			batchC = s.batchC
    92  		case batchC <- hashes:
    93  			hashes = nil
    94  			batchC = nil
    95  		}
    96  	}
    97  }
    98  
    99  // SessionIndex returns zero in all cases for SwarmChunkServer.
   100  func (s *SwarmChunkServer) SessionIndex() (uint64, error) {
   101  	return 0, nil
   102  }
   103  
   104  // SetNextBatch
   105  func (s *SwarmChunkServer) SetNextBatch(_, _ uint64) (hashes []byte, from uint64, to uint64, proof *HandoverProof, err error) {
   106  	select {
   107  	case hashes = <-s.batchC:
   108  	case <-s.quit:
   109  		return
   110  	}
   111  
   112  	from = s.currentLen
   113  	s.currentLen += uint64(len(hashes))
   114  	to = s.currentLen
   115  	return
   116  }
   117  
   118  // Close needs to be called on a stream server
   119  func (s *SwarmChunkServer) Close() {
   120  	close(s.quit)
   121  }
   122  
   123  // GetData retrives chunk data from db store
   124  func (s *SwarmChunkServer) GetData(ctx context.Context, key []byte) ([]byte, error) {
   125  	chunk, err := s.chunkStore.Get(ctx, storage.Address(key))
   126  	if err != nil {
   127  		return nil, err
   128  	}
   129  	return chunk.Data(), nil
   130  }
   131  
   132  // RetrieveRequestMsg is the protocol msg for chunk retrieve requests
   133  type RetrieveRequestMsg struct {
   134  	Addr      storage.Address
   135  	SkipCheck bool
   136  	HopCount  uint8
   137  }
   138  
   139  func (d *Delivery) handleRetrieveRequestMsg(ctx context.Context, sp *Peer, req *RetrieveRequestMsg) error {
   140  	log.Trace("received request", "peer", sp.ID(), "hash", req.Addr)
   141  	handleRetrieveRequestMsgCount.Inc(1)
   142  
   143  	var osp opentracing.Span
   144  	ctx, osp = spancontext.StartSpan(
   145  		ctx,
   146  		"retrieve.request")
   147  	defer osp.Finish()
   148  
   149  	s, err := sp.getServer(NewStream(swarmChunkServerStreamName, "", true))
   150  	if err != nil {
   151  		return err
   152  	}
   153  	streamer := s.Server.(*SwarmChunkServer)
   154  
   155  	var cancel func()
   156  	// TODO: do something with this hardcoded timeout, maybe use TTL in the future
   157  	ctx = context.WithValue(ctx, "peer", sp.ID().String())
   158  	ctx = context.WithValue(ctx, "hopcount", req.HopCount)
   159  	ctx, cancel = context.WithTimeout(ctx, network.RequestTimeout)
   160  
   161  	go func() {
   162  		select {
   163  		case <-ctx.Done():
   164  		case <-streamer.quit:
   165  		}
   166  		cancel()
   167  	}()
   168  
   169  	go func() {
   170  		chunk, err := d.chunkStore.Get(ctx, req.Addr)
   171  		if err != nil {
   172  			retrieveChunkFail.Inc(1)
   173  			log.Debug("ChunkStore.Get can not retrieve chunk", "peer", sp.ID().String(), "addr", req.Addr, "hopcount", req.HopCount, "err", err)
   174  			return
   175  		}
   176  		if req.SkipCheck {
   177  			syncing := false
   178  			err = sp.Deliver(ctx, chunk, s.priority, syncing)
   179  			if err != nil {
   180  				log.Warn("ERROR in handleRetrieveRequestMsg", "err", err)
   181  			}
   182  			return
   183  		}
   184  		select {
   185  		case streamer.deliveryC <- chunk.Address()[:]:
   186  		case <-streamer.quit:
   187  		}
   188  
   189  	}()
   190  
   191  	return nil
   192  }
   193  
   194  //Chunk delivery always uses the same message type....
   195  type ChunkDeliveryMsg struct {
   196  	Addr  storage.Address
   197  	SData []byte // the stored chunk Data (incl size)
   198  	peer  *Peer  // set in handleChunkDeliveryMsg
   199  }
   200  
   201  //...but swap accounting needs to disambiguate if it is a delivery for syncing or for retrieval
   202  //as it decides based on message type if it needs to account for this message or not
   203  
   204  //defines a chunk delivery for retrieval (with accounting)
   205  type ChunkDeliveryMsgRetrieval ChunkDeliveryMsg
   206  
   207  //defines a chunk delivery for syncing (without accounting)
   208  type ChunkDeliveryMsgSyncing ChunkDeliveryMsg
   209  
   210  // TODO: Fix context SNAFU
   211  func (d *Delivery) handleChunkDeliveryMsg(ctx context.Context, sp *Peer, req *ChunkDeliveryMsg) error {
   212  	var osp opentracing.Span
   213  	ctx, osp = spancontext.StartSpan(
   214  		ctx,
   215  		"chunk.delivery")
   216  	defer osp.Finish()
   217  
   218  	processReceivedChunksCount.Inc(1)
   219  
   220  	go func() {
   221  		req.peer = sp
   222  		err := d.chunkStore.Put(ctx, storage.NewChunk(req.Addr, req.SData))
   223  		if err != nil {
   224  			if err == storage.ErrChunkInvalid {
   225  				// we removed this log because it spams the logs
   226  				// TODO: Enable this log line
   227  				// log.Warn("invalid chunk delivered", "peer", sp.ID(), "chunk", req.Addr, )
   228  				req.peer.Drop(err)
   229  			}
   230  		}
   231  	}()
   232  	return nil
   233  }
   234  
   235  // RequestFromPeers sends a chunk retrieve request to
   236  func (d *Delivery) RequestFromPeers(ctx context.Context, req *network.Request) (*enode.ID, chan struct{}, error) {
   237  	requestFromPeersCount.Inc(1)
   238  	var sp *Peer
   239  	spID := req.Source
   240  
   241  	if spID != nil {
   242  		sp = d.getPeer(*spID)
   243  		if sp == nil {
   244  			return nil, nil, fmt.Errorf("source peer %v not found", spID.String())
   245  		}
   246  	} else {
   247  		d.kad.EachConn(req.Addr[:], 255, func(p *network.Peer, po int) bool {
   248  			id := p.ID()
   249  			if p.LightNode {
   250  				// skip light nodes
   251  				return true
   252  			}
   253  			if req.SkipPeer(id.String()) {
   254  				log.Trace("Delivery.RequestFromPeers: skip peer", "peer id", id)
   255  				return true
   256  			}
   257  			sp = d.getPeer(id)
   258  			if sp == nil {
   259  				//log.Warn("Delivery.RequestFromPeers: peer not found", "id", id)
   260  				return true
   261  			}
   262  			spID = &id
   263  			return false
   264  		})
   265  		if sp == nil {
   266  			return nil, nil, errors.New("no peer found")
   267  		}
   268  	}
   269  
   270  	err := sp.SendPriority(ctx, &RetrieveRequestMsg{
   271  		Addr:      req.Addr,
   272  		SkipCheck: req.SkipCheck,
   273  		HopCount:  req.HopCount,
   274  	}, Top)
   275  	if err != nil {
   276  		return nil, nil, err
   277  	}
   278  	requestFromPeersEachCount.Inc(1)
   279  
   280  	return spID, sp.quit, nil
   281  }