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
	"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
97
	done   chan struct{}
Jeromy's avatar
Jeromy committed
98 99
}

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

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

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

117 118 119
	stream, err := s.bsnet.newStreamToPeer(ctx, s.to)
	if err != nil {
		return nil, err
120
	}
121 122 123

	s.stream = stream
	return s.stream, nil
Jeromy's avatar
Jeromy committed
124 125
}

126
// Reset the stream
127
func (s *streamMessageSender) Reset() error {
128 129 130 131 132 133
	if s.stream != nil {
		err := s.stream.Reset()
		s.stream = nil
		return err
	}
	return nil
134 135
}

136
// Close the stream
137
func (s *streamMessageSender) Close() error {
138
	close(s.done)
139
	return helpers.FullClose(s.stream)
140 141
}

142
// Indicates whether the peer supports HAVE / DONT_HAVE messages
dirkmc's avatar
dirkmc committed
143
func (s *streamMessageSender) SupportsHave() bool {
144 145 146
	return s.bsnet.SupportsHave(s.stream.Protocol())
}

147
// Send a message to the peer, attempting multiple times
148
func (s *streamMessageSender) SendMsg(ctx context.Context, msg bsmsg.BitSwapMessage) error {
149 150 151 152 153 154 155 156
	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
157 158
	var err error
	for i := 0; i < s.opts.MaxRetries; i++ {
159 160 161 162 163 164
		deadline := time.Now().Add(s.opts.SendTimeout)
		sndctx, cancel := context.WithDeadline(ctx, deadline)

		if err = fn(sndctx); err == nil {
			cancel()
			// Attempt was successful
165 166
			return nil
		}
167
		cancel()
168

169 170
		// Attempt failed

171 172 173 174 175 176 177 178 179
		// 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:
		}

180 181 182 183 184 185
		// 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
		}

186 187 188
		// Failed to send so reset stream and try again
		_ = s.Reset()

189
		// Failed too many times so mark the peer as unresponsive and return an error
190
		if i == s.opts.MaxRetries-1 {
191 192 193 194 195 196 197
			s.bsnet.connectEvtMgr.MarkUnresponsive(s.to)
			return err
		}

		select {
		case <-ctx.Done():
			return nil
198 199
		case <-s.done:
			return nil
200 201 202 203 204 205 206 207
		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
}

208 209 210
// Send a message to the peer
func (s *streamMessageSender) send(ctx context.Context, msg bsmsg.BitSwapMessage) error {
	stream, err := s.Connect(ctx)
211 212 213 214 215
	if err != nil {
		log.Infof("failed to open stream to %s: %s", s.to, err)
		return err
	}

216
	if err = s.bsnet.msgToStream(ctx, stream, msg); err != nil {
217 218 219 220 221
		log.Infof("failed to send message to %s: %s", s.to, err)
		return err
	}

	return nil
dirkmc's avatar
dirkmc committed
222 223 224 225 226 227
}

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

228 229 230 231 232 233 234 235 236 237 238
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
239 240 241 242 243 244 245 246 247
// 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
}

248
func (bsnet *impl) msgToStream(ctx context.Context, s network.Stream, msg bsmsg.BitSwapMessage) error {
249 250 251 252
	deadline := time.Now().Add(sendMessageTimeout)
	if dl, ok := ctx.Deadline(); ok {
		deadline = dl
	}
Bob Potter's avatar
Bob Potter committed
253

254
	if err := s.SetWriteDeadline(deadline); err != nil {
255
		log.Warnf("error setting deadline: %s", err)
256 257
	}

dirkmc's avatar
dirkmc committed
258 259 260
	// 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.
261
	switch s.Protocol() {
dirkmc's avatar
dirkmc committed
262
	case bsnet.protocolBitswapOneOne, bsnet.protocolBitswap:
Bob Potter's avatar
Bob Potter committed
263
		if err := msg.ToNetV1(s); err != nil {
264 265 266
			log.Debugf("error: %s", err)
			return err
		}
dirkmc's avatar
dirkmc committed
267
	case bsnet.protocolBitswapOneZero, bsnet.protocolBitswapNoVers:
Bob Potter's avatar
Bob Potter committed
268
		if err := msg.ToNetV0(s); err != nil {
269 270 271 272 273 274
			log.Debugf("error: %s", err)
			return err
		}
	default:
		return fmt.Errorf("unrecognized protocol on remote: %s", s.Protocol())
	}
275 276

	if err := s.SetWriteDeadline(time.Time{}); err != nil {
277
		log.Warnf("error resetting deadline: %s", err)
278
	}
279
	return nil
Jeromy's avatar
Jeromy committed
280 281
}

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

285 286 287 288
	sender := &streamMessageSender{
		to:    p,
		bsnet: bsnet,
		opts:  opts,
289
		done:  make(chan struct{}),
Jeromy's avatar
Jeromy committed
290 291
	}

292 293 294 295
	err := sender.multiAttempt(ctx, func(fnctx context.Context) error {
		_, err := sender.Connect(fnctx)
		return err
	})
Jeromy's avatar
Jeromy committed
296

297 298 299
	if err != nil {
		return nil, err
	}
300

301
	return sender, nil
302 303
}

Dirk McCormick's avatar
Dirk McCormick committed
304 305 306 307 308 309 310 311 312 313 314 315 316 317
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
}

318 319 320 321 322 323
func (bsnet *impl) SendMessage(
	ctx context.Context,
	p peer.ID,
	outgoing bsmsg.BitSwapMessage) error {

	s, err := bsnet.newStreamToPeer(ctx, p)
324 325 326
	if err != nil {
		return err
	}
327

328
	if err = bsnet.msgToStream(ctx, s, outgoing); err != nil {
Steven Allen's avatar
Steven Allen committed
329
		_ = s.Reset()
Steven Allen's avatar
Steven Allen committed
330
		return err
331
	}
332 333
	atomic.AddUint64(&bsnet.stats.MessagesSent, 1)

334
	// TODO(https://github.com/libp2p/go-libp2p-net/issues/28): Avoid this goroutine.
Steven Allen's avatar
Steven Allen committed
335
	//nolint
Raúl Kripalani's avatar
Raúl Kripalani committed
336
	go helpers.AwaitEOF(s)
337
	return s.Close()
338
}
339

340 341
func (bsnet *impl) newStreamToPeer(ctx context.Context, p peer.ID) (network.Stream, error) {
	return bsnet.host.NewStream(ctx, p, bsnet.supportedProtocols...)
342 343
}

344 345
func (bsnet *impl) SetDelegate(r Receiver) {
	bsnet.receiver = r
346
	bsnet.connectEvtMgr = newConnectEventManager(r)
dirkmc's avatar
dirkmc committed
347 348 349
	for _, proto := range bsnet.supportedProtocols {
		bsnet.host.SetStreamHandler(proto, bsnet.handleNewStream)
	}
hannahhoward's avatar
hannahhoward committed
350 351 352
	bsnet.host.Network().Notify((*netNotifiee)(bsnet))
	// TODO: StopNotify.

353
}
354

355
func (bsnet *impl) ConnectTo(ctx context.Context, p peer.ID) error {
Raúl Kripalani's avatar
Raúl Kripalani committed
356
	return bsnet.host.Connect(ctx, peer.AddrInfo{ID: p})
357 358
}

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

363
// FindProvidersAsync returns a channel of providers for the given key.
364
func (bsnet *impl) FindProvidersAsync(ctx context.Context, k cid.Cid, max int) <-chan peer.ID {
365
	out := make(chan peer.ID, max)
366 367
	go func() {
		defer close(out)
368
		providers := bsnet.routing.FindProvidersAsync(ctx, k, max)
369
		for info := range providers {
370 371
			if info.ID == bsnet.host.ID() {
				continue // ignore self as provider
372
			}
Raúl Kripalani's avatar
Raúl Kripalani committed
373
			bsnet.host.Peerstore().AddAddrs(info.ID, info.Addrs, peerstore.TempAddrTTL)
374 375
			select {
			case <-ctx.Done():
376
				return
377 378 379 380 381
			case out <- info.ID:
			}
		}
	}()
	return out
382 383 384
}

// Provide provides the key to the network
385
func (bsnet *impl) Provide(ctx context.Context, k cid.Cid) error {
386
	return bsnet.routing.Provide(ctx, k, true)
387 388
}

389
// handleNewStream receives a new stream from the network.
Raúl Kripalani's avatar
Raúl Kripalani committed
390
func (bsnet *impl) handleNewStream(s network.Stream) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
391
	defer s.Close()
392 393

	if bsnet.receiver == nil {
Steven Allen's avatar
Steven Allen committed
394
		_ = s.Reset()
395 396 397
		return
	}

Steven Allen's avatar
Steven Allen committed
398
	reader := msgio.NewVarintReaderSize(s, network.MessageSizeMax)
399
	for {
Steven Allen's avatar
Steven Allen committed
400
		received, err := bsmsg.FromMsgReader(reader)
401
		if err != nil {
Jeromy's avatar
Jeromy committed
402
			if err != io.EOF {
Steven Allen's avatar
Steven Allen committed
403
				_ = s.Reset()
Jeromy's avatar
Jeromy committed
404 405 406
				go bsnet.receiver.ReceiveError(err)
				log.Debugf("bitswap net handleNewStream from %s error: %s", s.Conn().RemotePeer(), err)
			}
407 408
			return
		}
409

410 411 412
		p := s.Conn().RemotePeer()
		ctx := context.Background()
		log.Debugf("bitswap net handleNewStream from %s", s.Conn().RemotePeer())
413
		bsnet.connectEvtMgr.OnMessage(s.Conn().RemotePeer())
414
		bsnet.receiver.ReceiveMessage(ctx, p, received)
415
		atomic.AddUint64(&bsnet.stats.MessagesRecvd, 1)
416
	}
417
}
418

Raúl Kripalani's avatar
Raúl Kripalani committed
419
func (bsnet *impl) ConnectionManager() connmgr.ConnManager {
420 421 422
	return bsnet.host.ConnManager()
}

423 424
func (bsnet *impl) Stats() Stats {
	return Stats{
425 426 427 428 429
		MessagesRecvd: atomic.LoadUint64(&bsnet.stats.MessagesRecvd),
		MessagesSent:  atomic.LoadUint64(&bsnet.stats.MessagesSent),
	}
}

430 431 432 433 434 435
type netNotifiee impl

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

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