ipfs_impl.go 10.2 KB
Newer Older
1 2 3
package network

import (
4
	"context"
5
	"fmt"
Jeromy's avatar
Jeromy committed
6
	"io"
7
	"sync/atomic"
8
	"time"
Jeromy's avatar
Jeromy committed
9

Jeromy's avatar
Jeromy committed
10 11 12 13
	bsmsg "github.com/ipfs/go-bitswap/message"

	cid "github.com/ipfs/go-cid"
	logging "github.com/ipfs/go-log"
Raúl Kripalani's avatar
Raúl Kripalani committed
14
	"github.com/libp2p/go-libp2p-core/connmgr"
15
	"github.com/libp2p/go-libp2p-core/helpers"
Raúl Kripalani's avatar
Raúl Kripalani committed
16 17 18 19
	"github.com/libp2p/go-libp2p-core/host"
	"github.com/libp2p/go-libp2p-core/network"
	"github.com/libp2p/go-libp2p-core/peer"
	peerstore "github.com/libp2p/go-libp2p-core/peerstore"
20
	"github.com/libp2p/go-libp2p-core/protocol"
Raúl Kripalani's avatar
Raúl Kripalani committed
21
	"github.com/libp2p/go-libp2p-core/routing"
22
	"github.com/libp2p/go-libp2p/p2p/protocol/ping"
Steven Allen's avatar
Steven Allen committed
23
	msgio "github.com/libp2p/go-msgio"
Jeromy's avatar
Jeromy committed
24
	ma "github.com/multiformats/go-multiaddr"
25 26
)

Jeromy's avatar
Jeromy committed
27
var log = logging.Logger("bitswap_network")
Jeromy's avatar
Jeromy committed
28

29 30
var sendMessageTimeout = time.Minute * 10

31
// NewFromIpfsHost returns a BitSwapNetwork supported by underlying IPFS host.
32
func NewFromIpfsHost(host host.Host, r routing.ContentRouting, opts ...NetOpt) BitSwapNetwork {
dirkmc's avatar
dirkmc committed
33
	s := processSettings(opts...)
34

35
	bitswapNetwork := impl{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
36
		host:    host,
37
		routing: r,
38

dirkmc's avatar
dirkmc committed
39 40 41 42 43 44
		protocolBitswapNoVers:  s.ProtocolPrefix + ProtocolBitswapNoVers,
		protocolBitswapOneZero: s.ProtocolPrefix + ProtocolBitswapOneZero,
		protocolBitswapOneOne:  s.ProtocolPrefix + ProtocolBitswapOneOne,
		protocolBitswap:        s.ProtocolPrefix + ProtocolBitswap,

		supportedProtocols: s.SupportedProtocols,
45
	}
46

47
	return &bitswapNetwork
48 49
}

dirkmc's avatar
dirkmc committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
func processSettings(opts ...NetOpt) Settings {
	s := Settings{
		SupportedProtocols: []protocol.ID{
			ProtocolBitswap,
			ProtocolBitswapOneOne,
			ProtocolBitswapOneZero,
			ProtocolBitswapNoVers,
		},
	}
	for _, opt := range opts {
		opt(&s)
	}
	for i, proto := range s.SupportedProtocols {
		s.SupportedProtocols[i] = s.ProtocolPrefix + proto
	}
	return s
}

68 69
// impl transforms the ipfs network interface, which sends and receives
// NetMessage objects, into the bitswap network interface.
70
type impl struct {
Steven Allen's avatar
Steven Allen committed
71 72 73 74
	// NOTE: Stats must be at the top of the heap allocation to ensure 64bit
	// alignment.
	stats Stats

75 76 77
	host          host.Host
	routing       routing.ContentRouting
	connectEvtMgr *connectEventManager
78

dirkmc's avatar
dirkmc committed
79 80 81 82 83 84
	protocolBitswapNoVers  protocol.ID
	protocolBitswapOneZero protocol.ID
	protocolBitswapOneOne  protocol.ID
	protocolBitswap        protocol.ID

	supportedProtocols []protocol.ID
85

86 87
	// inbound messages from the network are forwarded to the receiver
	receiver Receiver
88 89
}

Jeromy's avatar
Jeromy committed
90
type streamMessageSender struct {
91 92 93 94
	to     peer.ID
	stream network.Stream
	bsnet  *impl
	opts   *MessageSenderOpts
95
	done   chan struct{}
Jeromy's avatar
Jeromy committed
96 97
}

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
func (s *streamMessageSender) Connect(ctx context.Context) (stream network.Stream, err error) {
	defer func() {
		if err != nil {
			s.bsnet.connectEvtMgr.MarkUnresponsive(s.to)
		}
	}()

	if s.stream != nil {
		return s.stream, nil
	}

	if err = s.bsnet.ConnectTo(ctx, s.to); err != nil {
		return nil, err
	}

113 114 115 116 117 118 119
	// Check if the sender has been closed
	select {
	case <-s.done:
		return nil, nil
	default:
	}

120
	stream, err = s.bsnet.newStreamToPeer(ctx, s.to)
Dirk McCormick's avatar
Dirk McCormick committed
121
	if err == nil {
122 123 124 125
		s.stream = stream
		return s.stream, nil
	}
	return nil, err
Jeromy's avatar
Jeromy committed
126 127
}

128
func (s *streamMessageSender) Reset() error {
129 130 131
	err := s.stream.Reset()
	s.stream = nil
	return err
132 133
}

134
func (s *streamMessageSender) Close() error {
135
	close(s.done)
136
	return helpers.FullClose(s.stream)
137 138
}

dirkmc's avatar
dirkmc committed
139
func (s *streamMessageSender) SupportsHave() bool {
140 141 142 143 144 145 146 147 148 149 150 151
	return s.bsnet.SupportsHave(s.stream.Protocol())
}

func (s *streamMessageSender) SendMsg(ctx context.Context, msg bsmsg.BitSwapMessage) error {
	// Try to send the message repeatedly
	var err error
	for i := 0; i < s.opts.MaxRetries; i++ {
		if err = s.attemptSend(ctx, msg); err == nil {
			// Sent successfully
			return nil
		}

152 153 154 155 156 157 158 159 160
		// If the sender has been closed or the context cancelled, just bail out
		select {
		case <-ctx.Done():
			return nil
		case <-s.done:
			return nil
		default:
		}

161 162 163 164 165 166 167 168 169 170 171
		// Failed to send so reset stream and try again
		_ = s.Reset()

		if i == s.opts.MaxRetries {
			s.bsnet.connectEvtMgr.MarkUnresponsive(s.to)
			return err
		}

		select {
		case <-ctx.Done():
			return nil
172 173
		case <-s.done:
			return nil
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
		case <-time.After(s.opts.SendErrorBackoff):
			// wait a short time in case disconnect notifications are still propagating
			log.Infof("send message to %s failed but context was not Done: %s", s.to, err)
		}
	}
	return err
}

func (s *streamMessageSender) attemptSend(ctx context.Context, msg bsmsg.BitSwapMessage) error {
	sndctx, cancel := context.WithTimeout(ctx, s.opts.SendTimeout)
	defer cancel()

	stream, err := s.Connect(sndctx)
	if err != nil {
		log.Infof("failed to open stream to %s: %s", s.to, err)
		return err
	}

	if err = s.bsnet.msgToStream(sndctx, stream, msg); err != nil {
		log.Infof("failed to send message to %s: %s", s.to, err)
		return err
	}

	return nil
dirkmc's avatar
dirkmc committed
198 199 200 201 202 203
}

func (bsnet *impl) Self() peer.ID {
	return bsnet.host.ID()
}

204 205 206 207 208 209 210 211 212 213 214
func (bsnet *impl) Ping(ctx context.Context, p peer.ID) ping.Result {
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	res := <-ping.Ping(ctx, bsnet.host, p)
	return res
}

func (bsnet *impl) Latency(p peer.ID) time.Duration {
	return bsnet.host.Peerstore().LatencyEWMA(p)
}

dirkmc's avatar
dirkmc committed
215 216 217 218 219 220 221 222 223
// Indicates whether the given protocol supports HAVE / DONT_HAVE messages
func (bsnet *impl) SupportsHave(proto protocol.ID) bool {
	switch proto {
	case bsnet.protocolBitswapOneOne, bsnet.protocolBitswapOneZero, bsnet.protocolBitswapNoVers:
		return false
	}
	return true
}

224
func (bsnet *impl) msgToStream(ctx context.Context, s network.Stream, msg bsmsg.BitSwapMessage) error {
225 226 227 228
	deadline := time.Now().Add(sendMessageTimeout)
	if dl, ok := ctx.Deadline(); ok {
		deadline = dl
	}
Bob Potter's avatar
Bob Potter committed
229

230
	if err := s.SetWriteDeadline(deadline); err != nil {
231
		log.Warnf("error setting deadline: %s", err)
232 233
	}

dirkmc's avatar
dirkmc committed
234 235 236
	// Older Bitswap versions use a slightly different wire format so we need
	// to convert the message to the appropriate format depending on the remote
	// peer's Bitswap version.
237
	switch s.Protocol() {
dirkmc's avatar
dirkmc committed
238
	case bsnet.protocolBitswapOneOne, bsnet.protocolBitswap:
Bob Potter's avatar
Bob Potter committed
239
		if err := msg.ToNetV1(s); err != nil {
240 241 242
			log.Debugf("error: %s", err)
			return err
		}
dirkmc's avatar
dirkmc committed
243
	case bsnet.protocolBitswapOneZero, bsnet.protocolBitswapNoVers:
Bob Potter's avatar
Bob Potter committed
244
		if err := msg.ToNetV0(s); err != nil {
245 246 247 248 249 250
			log.Debugf("error: %s", err)
			return err
		}
	default:
		return fmt.Errorf("unrecognized protocol on remote: %s", s.Protocol())
	}
251 252

	if err := s.SetWriteDeadline(time.Time{}); err != nil {
253
		log.Warnf("error resetting deadline: %s", err)
254
	}
255
	return nil
Jeromy's avatar
Jeromy committed
256 257
}

258 259 260 261 262
func (bsnet *impl) NewMessageSender(ctx context.Context, p peer.ID, opts *MessageSenderOpts) (MessageSender, error) {
	sender := &streamMessageSender{
		to:    p,
		bsnet: bsnet,
		opts:  opts,
263
		done:  make(chan struct{}),
Jeromy's avatar
Jeromy committed
264 265
	}

266 267
	conctx, cancel := context.WithTimeout(ctx, sender.opts.SendTimeout)
	defer cancel()
Jeromy's avatar
Jeromy committed
268

269 270 271 272 273
	_, err := sender.Connect(conctx)
	if err != nil {
		return nil, err
	}
	return sender, nil
274 275 276 277 278 279 280 281
}

func (bsnet *impl) SendMessage(
	ctx context.Context,
	p peer.ID,
	outgoing bsmsg.BitSwapMessage) error {

	s, err := bsnet.newStreamToPeer(ctx, p)
282 283 284
	if err != nil {
		return err
	}
285

286
	if err = bsnet.msgToStream(ctx, s, outgoing); err != nil {
Steven Allen's avatar
Steven Allen committed
287
		_ = s.Reset()
Steven Allen's avatar
Steven Allen committed
288
		return err
289
	}
290 291
	atomic.AddUint64(&bsnet.stats.MessagesSent, 1)

292
	// TODO(https://github.com/libp2p/go-libp2p-net/issues/28): Avoid this goroutine.
Steven Allen's avatar
Steven Allen committed
293
	//nolint
Raúl Kripalani's avatar
Raúl Kripalani committed
294
	go helpers.AwaitEOF(s)
295
	return s.Close()
296
}
297

298 299
func (bsnet *impl) newStreamToPeer(ctx context.Context, p peer.ID) (network.Stream, error) {
	return bsnet.host.NewStream(ctx, p, bsnet.supportedProtocols...)
300 301
}

302 303
func (bsnet *impl) SetDelegate(r Receiver) {
	bsnet.receiver = r
304
	bsnet.connectEvtMgr = newConnectEventManager(r)
dirkmc's avatar
dirkmc committed
305 306 307
	for _, proto := range bsnet.supportedProtocols {
		bsnet.host.SetStreamHandler(proto, bsnet.handleNewStream)
	}
hannahhoward's avatar
hannahhoward committed
308 309 310
	bsnet.host.Network().Notify((*netNotifiee)(bsnet))
	// TODO: StopNotify.

311
}
312

313
func (bsnet *impl) ConnectTo(ctx context.Context, p peer.ID) error {
Raúl Kripalani's avatar
Raúl Kripalani committed
314
	return bsnet.host.Connect(ctx, peer.AddrInfo{ID: p})
315 316
}

dirkmc's avatar
dirkmc committed
317 318 319 320
func (bsnet *impl) DisconnectFrom(ctx context.Context, p peer.ID) error {
	panic("Not implemented: DisconnectFrom() is only used by tests")
}

321
// FindProvidersAsync returns a channel of providers for the given key.
322
func (bsnet *impl) FindProvidersAsync(ctx context.Context, k cid.Cid, max int) <-chan peer.ID {
323
	out := make(chan peer.ID, max)
324 325
	go func() {
		defer close(out)
326
		providers := bsnet.routing.FindProvidersAsync(ctx, k, max)
327
		for info := range providers {
328 329
			if info.ID == bsnet.host.ID() {
				continue // ignore self as provider
330
			}
Raúl Kripalani's avatar
Raúl Kripalani committed
331
			bsnet.host.Peerstore().AddAddrs(info.ID, info.Addrs, peerstore.TempAddrTTL)
332 333
			select {
			case <-ctx.Done():
334
				return
335 336 337 338 339
			case out <- info.ID:
			}
		}
	}()
	return out
340 341 342
}

// Provide provides the key to the network
343
func (bsnet *impl) Provide(ctx context.Context, k cid.Cid) error {
344
	return bsnet.routing.Provide(ctx, k, true)
345 346
}

347
// handleNewStream receives a new stream from the network.
Raúl Kripalani's avatar
Raúl Kripalani committed
348
func (bsnet *impl) handleNewStream(s network.Stream) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
349
	defer s.Close()
350 351

	if bsnet.receiver == nil {
Steven Allen's avatar
Steven Allen committed
352
		_ = s.Reset()
353 354 355
		return
	}

Steven Allen's avatar
Steven Allen committed
356
	reader := msgio.NewVarintReaderSize(s, network.MessageSizeMax)
357
	for {
Steven Allen's avatar
Steven Allen committed
358
		received, err := bsmsg.FromMsgReader(reader)
359
		if err != nil {
Jeromy's avatar
Jeromy committed
360
			if err != io.EOF {
Steven Allen's avatar
Steven Allen committed
361
				_ = s.Reset()
Jeromy's avatar
Jeromy committed
362 363 364
				go bsnet.receiver.ReceiveError(err)
				log.Debugf("bitswap net handleNewStream from %s error: %s", s.Conn().RemotePeer(), err)
			}
365 366
			return
		}
367

368 369 370
		p := s.Conn().RemotePeer()
		ctx := context.Background()
		log.Debugf("bitswap net handleNewStream from %s", s.Conn().RemotePeer())
371
		bsnet.connectEvtMgr.OnMessage(s.Conn().RemotePeer())
372
		bsnet.receiver.ReceiveMessage(ctx, p, received)
373
		atomic.AddUint64(&bsnet.stats.MessagesRecvd, 1)
374
	}
375
}
376

Raúl Kripalani's avatar
Raúl Kripalani committed
377
func (bsnet *impl) ConnectionManager() connmgr.ConnManager {
378 379 380
	return bsnet.host.ConnManager()
}

381 382
func (bsnet *impl) Stats() Stats {
	return Stats{
383 384 385 386 387
		MessagesRecvd: atomic.LoadUint64(&bsnet.stats.MessagesRecvd),
		MessagesSent:  atomic.LoadUint64(&bsnet.stats.MessagesSent),
	}
}

388 389 390 391 392 393
type netNotifiee impl

func (nn *netNotifiee) impl() *impl {
	return (*impl)(nn)
}

Raúl Kripalani's avatar
Raúl Kripalani committed
394
func (nn *netNotifiee) Connected(n network.Network, v network.Conn) {
395
	nn.impl().connectEvtMgr.Connected(v.RemotePeer())
396
}
Raúl Kripalani's avatar
Raúl Kripalani committed
397
func (nn *netNotifiee) Disconnected(n network.Network, v network.Conn) {
398
	nn.impl().connectEvtMgr.Disconnected(v.RemotePeer())
399
}
dirkmc's avatar
dirkmc committed
400
func (nn *netNotifiee) OpenedStream(n network.Network, s network.Stream) {}
Raúl Kripalani's avatar
Raúl Kripalani committed
401 402 403
func (nn *netNotifiee) ClosedStream(n network.Network, v network.Stream) {}
func (nn *netNotifiee) Listen(n network.Network, a ma.Multiaddr)         {}
func (nn *netNotifiee) ListenClose(n network.Network, a ma.Multiaddr)    {}