ipfs_impl.go 11.1 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
	"github.com/libp2p/go-libp2p-core/connmgr"
16
	"github.com/libp2p/go-libp2p-core/helpers"
Raúl Kripalani's avatar
Raúl Kripalani committed
17 18 19 20
	"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"
21
	"github.com/libp2p/go-libp2p-core/protocol"
Raúl Kripalani's avatar
Raúl Kripalani committed
22
	"github.com/libp2p/go-libp2p-core/routing"
23
	"github.com/libp2p/go-libp2p/p2p/protocol/ping"
Steven Allen's avatar
Steven Allen committed
24
	msgio "github.com/libp2p/go-msgio"
Jeromy's avatar
Jeromy committed
25
	ma "github.com/multiformats/go-multiaddr"
26
	"github.com/multiformats/go-multistream"
27 28
)

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

31 32
var sendMessageTimeout = time.Minute * 10

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

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

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

		supportedProtocols: s.SupportedProtocols,
47
	}
48

49
	return &bitswapNetwork
50 51
}

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

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

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

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

	supportedProtocols []protocol.ID
87

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

Jeromy's avatar
Jeromy committed
92
type streamMessageSender struct {
93 94 95 96
	to     peer.ID
	stream network.Stream
	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 102 103 104
	if s.stream != nil {
		return s.stream, nil
	}

105
	if err := s.bsnet.ConnectTo(ctx, s.to); err != nil {
106 107 108
		return nil, err
	}

109 110 111
	stream, err := s.bsnet.newStreamToPeer(ctx, s.to)
	if err != nil {
		return nil, err
112
	}
113 114 115

	s.stream = stream
	return s.stream, nil
Jeromy's avatar
Jeromy committed
116 117
}

118
// Reset the stream
119
func (s *streamMessageSender) Reset() error {
120 121 122 123 124 125
	if s.stream != nil {
		err := s.stream.Reset()
		s.stream = nil
		return err
	}
	return nil
126 127
}

128
// Close the stream
129 130
func (s *streamMessageSender) Close() error {
	return helpers.FullClose(s.stream)
131 132
}

133
// Indicates whether the peer supports HAVE / DONT_HAVE messages
dirkmc's avatar
dirkmc committed
134
func (s *streamMessageSender) SupportsHave() bool {
135 136 137
	return s.bsnet.SupportsHave(s.stream.Protocol())
}

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

// Perform a function with multiple attempts, and a timeout
func (s *streamMessageSender) multiAttempt(ctx context.Context, fn func(context.Context) error) error {
	// Try to call the function repeatedly
148 149
	var err error
	for i := 0; i < s.opts.MaxRetries; i++ {
150 151 152 153 154 155
		deadline := time.Now().Add(s.opts.SendTimeout)
		sndctx, cancel := context.WithDeadline(ctx, deadline)

		if err = fn(sndctx); err == nil {
			cancel()
			// Attempt was successful
156 157
			return nil
		}
158
		cancel()
159

160 161
		// Attempt failed

162 163 164 165 166 167 168
		// If the sender has been closed or the context cancelled, just bail out
		select {
		case <-ctx.Done():
			return nil
		default:
		}

169 170 171 172 173 174
		// 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
		}

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

178
		// Failed too many times so mark the peer as unresponsive and return an error
179
		if i == s.opts.MaxRetries-1 {
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
			s.bsnet.connectEvtMgr.MarkUnresponsive(s.to)
			return err
		}

		select {
		case <-ctx.Done():
			return nil
		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
}

195 196 197
// Send a message to the peer
func (s *streamMessageSender) send(ctx context.Context, msg bsmsg.BitSwapMessage) error {
	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
	if err = s.bsnet.msgToStream(ctx, stream, msg); err != nil {
204 205 206 207 208
		log.Infof("failed to send message to %s: %s", s.to, err)
		return err
	}

	return nil
dirkmc's avatar
dirkmc committed
209 210 211 212 213 214
}

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

215 216 217 218 219 220 221 222 223 224 225
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
226 227 228 229 230 231 232 233 234
// 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
}

235
func (bsnet *impl) msgToStream(ctx context.Context, s network.Stream, msg bsmsg.BitSwapMessage) error {
236 237 238 239
	deadline := time.Now().Add(sendMessageTimeout)
	if dl, ok := ctx.Deadline(); ok {
		deadline = dl
	}
Bob Potter's avatar
Bob Potter committed
240

241
	if err := s.SetWriteDeadline(deadline); err != nil {
242
		log.Warnf("error setting deadline: %s", err)
243 244
	}

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

	if err := s.SetWriteDeadline(time.Time{}); err != nil {
264
		log.Warnf("error resetting deadline: %s", err)
265
	}
266
	return nil
Jeromy's avatar
Jeromy committed
267 268
}

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

272 273 274 275
	sender := &streamMessageSender{
		to:    p,
		bsnet: bsnet,
		opts:  opts,
Jeromy's avatar
Jeromy committed
276 277
	}

278 279 280 281
	err := sender.multiAttempt(ctx, func(fnctx context.Context) error {
		_, err := sender.Connect(fnctx)
		return err
	})
Jeromy's avatar
Jeromy committed
282

283 284 285
	if err != nil {
		return nil, err
	}
286

287
	return sender, nil
288 289
}

Dirk McCormick's avatar
Dirk McCormick committed
290 291 292 293 294 295 296 297 298 299 300 301 302 303
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
}

304 305 306 307 308 309
func (bsnet *impl) SendMessage(
	ctx context.Context,
	p peer.ID,
	outgoing bsmsg.BitSwapMessage) error {

	s, err := bsnet.newStreamToPeer(ctx, p)
310 311 312
	if err != nil {
		return err
	}
313

314
	if err = bsnet.msgToStream(ctx, s, outgoing); err != nil {
Steven Allen's avatar
Steven Allen committed
315
		_ = s.Reset()
Steven Allen's avatar
Steven Allen committed
316
		return err
317
	}
318 319
	atomic.AddUint64(&bsnet.stats.MessagesSent, 1)

320
	// TODO(https://github.com/libp2p/go-libp2p-net/issues/28): Avoid this goroutine.
Steven Allen's avatar
Steven Allen committed
321
	//nolint
Raúl Kripalani's avatar
Raúl Kripalani committed
322
	go helpers.AwaitEOF(s)
323
	return s.Close()
324
}
325

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

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

339
}
340

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

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

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

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

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

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

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

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

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

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

416 417 418 419 420 421
type netNotifiee impl

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

Raúl Kripalani's avatar
Raúl Kripalani committed
422
func (nn *netNotifiee) Connected(n network.Network, v network.Conn) {
423
	nn.impl().connectEvtMgr.Connected(v.RemotePeer())
424
}
Raúl Kripalani's avatar
Raúl Kripalani committed
425
func (nn *netNotifiee) Disconnected(n network.Network, v network.Conn) {
426
	nn.impl().connectEvtMgr.Disconnected(v.RemotePeer())
427
}
dirkmc's avatar
dirkmc committed
428
func (nn *netNotifiee) OpenedStream(n network.Network, s network.Stream) {}
Raúl Kripalani's avatar
Raúl Kripalani committed
429 430 431
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)    {}