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

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

Jeromy's avatar
Jeromy committed
11 12 13 14
	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
15 16 17 18 19
	"github.com/libp2p/go-libp2p-core/connmgr"
	"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
	"github.com/multiformats/go-multistream"
26 27
)

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

30 31
var sendMessageTimeout = time.Minute * 10

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

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

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

		supportedProtocols: s.SupportedProtocols,
46
	}
47

48
	return &bitswapNetwork
49 50
}

dirkmc's avatar
dirkmc committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
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
}

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

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

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

	supportedProtocols []protocol.ID
86

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

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

99 100
// Open a stream to the remote peer
func (s *streamMessageSender) Connect(ctx context.Context) (network.Stream, error) {
101
	if s.connected {
102 103 104
		return s.stream, nil
	}

105 106 107 108
	tctx, cancel := context.WithTimeout(ctx, s.opts.SendTimeout)
	defer cancel()

	if err := s.bsnet.ConnectTo(tctx, s.to); err != nil {
109 110 111
		return nil, err
	}

112
	stream, err := s.bsnet.newStreamToPeer(tctx, s.to)
113 114
	if err != nil {
		return nil, err
115
	}
116 117

	s.stream = stream
118
	s.connected = true
119
	return s.stream, nil
Jeromy's avatar
Jeromy committed
120 121
}

122
// Reset the stream
123
func (s *streamMessageSender) Reset() error {
124 125
	if s.stream != nil {
		err := s.stream.Reset()
126
		s.connected = false
127 128 129
		return err
	}
	return nil
130 131
}

132
// Close the stream
133
func (s *streamMessageSender) Close() error {
134
	return s.stream.Close()
135 136
}

137
// Indicates whether the peer supports HAVE / DONT_HAVE messages
dirkmc's avatar
dirkmc committed
138
func (s *streamMessageSender) SupportsHave() bool {
139 140 141
	return s.bsnet.SupportsHave(s.stream.Protocol())
}

142
// Send a message to the peer, attempting multiple times
143
func (s *streamMessageSender) SendMsg(ctx context.Context, msg bsmsg.BitSwapMessage) error {
144 145
	return s.multiAttempt(ctx, func() error {
		return s.send(ctx, msg)
146 147 148 149
	})
}

// Perform a function with multiple attempts, and a timeout
150
func (s *streamMessageSender) multiAttempt(ctx context.Context, fn func() error) error {
151
	// Try to call the function repeatedly
152 153
	var err error
	for i := 0; i < s.opts.MaxRetries; i++ {
154
		if err = fn(); err == nil {
155
			// Attempt was successful
156 157 158
			return nil
		}

159 160
		// Attempt failed

161 162 163
		// If the sender has been closed or the context cancelled, just bail out
		select {
		case <-ctx.Done():
Dirk McCormick's avatar
Dirk McCormick committed
164
			return ctx.Err()
165 166 167
		default:
		}

168 169 170 171 172 173
		// Protocol is not supported, so no need to try multiple times
		if errors.Is(err, multistream.ErrNotSupported) {
			s.bsnet.connectEvtMgr.MarkUnresponsive(s.to)
			return err
		}

174 175 176
		// Failed to send so reset stream and try again
		_ = s.Reset()

177
		// Failed too many times so mark the peer as unresponsive and return an error
178
		if i == s.opts.MaxRetries-1 {
179 180 181 182 183 184
			s.bsnet.connectEvtMgr.MarkUnresponsive(s.to)
			return err
		}

		select {
		case <-ctx.Done():
Dirk McCormick's avatar
Dirk McCormick committed
185
			return ctx.Err()
186 187 188 189 190 191 192 193
		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
}

194 195
// Send a message to the peer
func (s *streamMessageSender) send(ctx context.Context, msg bsmsg.BitSwapMessage) error {
196
	start := time.Now()
197
	stream, err := s.Connect(ctx)
198 199 200 201 202
	if err != nil {
		log.Infof("failed to open stream to %s: %s", s.to, err)
		return err
	}

203 204 205 206 207
	// The send timeout includes the time required to connect
	// (although usually we will already have connected - we only need to
	// connect after a failed attempt to send)
	timeout := s.opts.SendTimeout - time.Since(start)
	if err = s.bsnet.msgToStream(ctx, stream, msg, timeout); err != nil {
208 209 210 211 212
		log.Infof("failed to send message to %s: %s", s.to, err)
		return err
	}

	return nil
dirkmc's avatar
dirkmc committed
213 214 215 216 217 218
}

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

219 220 221 222 223 224 225 226 227 228 229
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
230 231 232 233 234 235 236 237 238
// 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
}

239 240 241
func (bsnet *impl) msgToStream(ctx context.Context, s network.Stream, msg bsmsg.BitSwapMessage, timeout time.Duration) error {
	deadline := time.Now().Add(timeout)
	if dl, ok := ctx.Deadline(); ok && dl.Before(deadline) {
242 243
		deadline = dl
	}
Bob Potter's avatar
Bob Potter committed
244

245
	if err := s.SetWriteDeadline(deadline); err != nil {
246
		log.Warnf("error setting deadline: %s", err)
247 248
	}

dirkmc's avatar
dirkmc committed
249 250 251
	// 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.
252
	switch s.Protocol() {
dirkmc's avatar
dirkmc committed
253
	case bsnet.protocolBitswapOneOne, bsnet.protocolBitswap:
Bob Potter's avatar
Bob Potter committed
254
		if err := msg.ToNetV1(s); err != nil {
255 256 257
			log.Debugf("error: %s", err)
			return err
		}
dirkmc's avatar
dirkmc committed
258
	case bsnet.protocolBitswapOneZero, bsnet.protocolBitswapNoVers:
Bob Potter's avatar
Bob Potter committed
259
		if err := msg.ToNetV0(s); err != nil {
260 261 262 263 264 265
			log.Debugf("error: %s", err)
			return err
		}
	default:
		return fmt.Errorf("unrecognized protocol on remote: %s", s.Protocol())
	}
266

267 268
	atomic.AddUint64(&bsnet.stats.MessagesSent, 1)

269
	if err := s.SetWriteDeadline(time.Time{}); err != nil {
270
		log.Warnf("error resetting deadline: %s", err)
271
	}
272
	return nil
Jeromy's avatar
Jeromy committed
273 274
}

275
func (bsnet *impl) NewMessageSender(ctx context.Context, p peer.ID, opts *MessageSenderOpts) (MessageSender, error) {
Dirk McCormick's avatar
Dirk McCormick committed
276
	opts = setDefaultOpts(opts)
277

278 279 280 281
	sender := &streamMessageSender{
		to:    p,
		bsnet: bsnet,
		opts:  opts,
Jeromy's avatar
Jeromy committed
282 283
	}

284 285
	err := sender.multiAttempt(ctx, func() error {
		_, err := sender.Connect(ctx)
286 287
		return err
	})
Jeromy's avatar
Jeromy committed
288 289 290 291 292

	if err != nil {
		return nil, err
	}

293
	return sender, nil
Jeromy's avatar
Jeromy committed
294 295
}

Dirk McCormick's avatar
Dirk McCormick committed
296 297 298 299 300 301 302 303 304 305 306 307
func setDefaultOpts(opts *MessageSenderOpts) *MessageSenderOpts {
	copy := *opts
	if opts.MaxRetries == 0 {
		copy.MaxRetries = 3
	}
	if opts.SendTimeout == 0 {
		copy.SendTimeout = sendMessageTimeout
	}
	if opts.SendErrorBackoff == 0 {
		copy.SendErrorBackoff = 100 * time.Millisecond
	}
	return &copy
308 309 310 311 312 313 314 315
}

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

	s, err := bsnet.newStreamToPeer(ctx, p)
316 317 318
	if err != nil {
		return err
	}
319

320
	if err = bsnet.msgToStream(ctx, s, outgoing, sendMessageTimeout); err != nil {
Steven Allen's avatar
Steven Allen committed
321
		_ = s.Reset()
Steven Allen's avatar
Steven Allen committed
322
		return err
323
	}
324

325
	return s.Close()
326
}
327

328 329
func (bsnet *impl) newStreamToPeer(ctx context.Context, p peer.ID) (network.Stream, error) {
	return bsnet.host.NewStream(ctx, p, bsnet.supportedProtocols...)
330 331
}

332 333
func (bsnet *impl) SetDelegate(r Receiver) {
	bsnet.receiver = r
334
	bsnet.connectEvtMgr = newConnectEventManager(r)
dirkmc's avatar
dirkmc committed
335 336 337
	for _, proto := range bsnet.supportedProtocols {
		bsnet.host.SetStreamHandler(proto, bsnet.handleNewStream)
	}
hannahhoward's avatar
hannahhoward committed
338 339 340
	bsnet.host.Network().Notify((*netNotifiee)(bsnet))
	// TODO: StopNotify.

341
}
342

343
func (bsnet *impl) ConnectTo(ctx context.Context, p peer.ID) error {
Raúl Kripalani's avatar
Raúl Kripalani committed
344
	return bsnet.host.Connect(ctx, peer.AddrInfo{ID: p})
345 346
}

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

351
// FindProvidersAsync returns a channel of providers for the given key.
352
func (bsnet *impl) FindProvidersAsync(ctx context.Context, k cid.Cid, max int) <-chan peer.ID {
353
	out := make(chan peer.ID, max)
354 355
	go func() {
		defer close(out)
356
		providers := bsnet.routing.FindProvidersAsync(ctx, k, max)
357
		for info := range providers {
358 359
			if info.ID == bsnet.host.ID() {
				continue // ignore self as provider
360
			}
Raúl Kripalani's avatar
Raúl Kripalani committed
361
			bsnet.host.Peerstore().AddAddrs(info.ID, info.Addrs, peerstore.TempAddrTTL)
362 363
			select {
			case <-ctx.Done():
364
				return
365 366 367 368 369
			case out <- info.ID:
			}
		}
	}()
	return out
370 371 372
}

// Provide provides the key to the network
373
func (bsnet *impl) Provide(ctx context.Context, k cid.Cid) error {
374
	return bsnet.routing.Provide(ctx, k, true)
375 376
}

377
// handleNewStream receives a new stream from the network.
Raúl Kripalani's avatar
Raúl Kripalani committed
378
func (bsnet *impl) handleNewStream(s network.Stream) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
379
	defer s.Close()
380 381

	if bsnet.receiver == nil {
Steven Allen's avatar
Steven Allen committed
382
		_ = s.Reset()
383 384 385
		return
	}

Steven Allen's avatar
Steven Allen committed
386
	reader := msgio.NewVarintReaderSize(s, network.MessageSizeMax)
387
	for {
Steven Allen's avatar
Steven Allen committed
388
		received, err := bsmsg.FromMsgReader(reader)
389
		if err != nil {
Jeromy's avatar
Jeromy committed
390
			if err != io.EOF {
Steven Allen's avatar
Steven Allen committed
391
				_ = s.Reset()
392
				bsnet.receiver.ReceiveError(err)
Jeromy's avatar
Jeromy committed
393 394
				log.Debugf("bitswap net handleNewStream from %s error: %s", s.Conn().RemotePeer(), err)
			}
395 396
			return
		}
397

398 399 400
		p := s.Conn().RemotePeer()
		ctx := context.Background()
		log.Debugf("bitswap net handleNewStream from %s", s.Conn().RemotePeer())
401
		bsnet.connectEvtMgr.OnMessage(s.Conn().RemotePeer())
402
		bsnet.receiver.ReceiveMessage(ctx, p, received)
403
		atomic.AddUint64(&bsnet.stats.MessagesRecvd, 1)
404
	}
405
}
406

Raúl Kripalani's avatar
Raúl Kripalani committed
407
func (bsnet *impl) ConnectionManager() connmgr.ConnManager {
408 409 410
	return bsnet.host.ConnManager()
}

411 412
func (bsnet *impl) Stats() Stats {
	return Stats{
413 414 415 416 417
		MessagesRecvd: atomic.LoadUint64(&bsnet.stats.MessagesRecvd),
		MessagesSent:  atomic.LoadUint64(&bsnet.stats.MessagesSent),
	}
}

418 419 420 421 422 423
type netNotifiee impl

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

Raúl Kripalani's avatar
Raúl Kripalani committed
424
func (nn *netNotifiee) Connected(n network.Network, v network.Conn) {
vyzo's avatar
vyzo committed
425 426 427 428 429
	// ignore transient connections
	if v.Stat().Transient {
		return
	}

430
	nn.impl().connectEvtMgr.Connected(v.RemotePeer())
431
}
Raúl Kripalani's avatar
Raúl Kripalani committed
432
func (nn *netNotifiee) Disconnected(n network.Network, v network.Conn) {
vyzo's avatar
vyzo committed
433 434 435 436 437
	// ignore transient connections
	if v.Stat().Transient {
		return
	}

438
	nn.impl().connectEvtMgr.Disconnected(v.RemotePeer())
439
}
dirkmc's avatar
dirkmc committed
440
func (nn *netNotifiee) OpenedStream(n network.Network, s network.Stream) {}
Raúl Kripalani's avatar
Raúl Kripalani committed
441 442 443
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)    {}