bitswap.go 5.82 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package bitswap

import (
4
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
5
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
6

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
7
	blocks "github.com/jbenet/go-ipfs/blocks"
8
	blockstore "github.com/jbenet/go-ipfs/blockstore"
9 10 11 12 13
	exchange "github.com/jbenet/go-ipfs/exchange"
	bsmsg "github.com/jbenet/go-ipfs/exchange/bitswap/message"
	bsnet "github.com/jbenet/go-ipfs/exchange/bitswap/network"
	notifications "github.com/jbenet/go-ipfs/exchange/bitswap/notifications"
	strategy "github.com/jbenet/go-ipfs/exchange/bitswap/strategy"
14
	inet "github.com/jbenet/go-ipfs/net"
15
	peer "github.com/jbenet/go-ipfs/peer"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
16
	u "github.com/jbenet/go-ipfs/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17 18
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
19 20
var log = u.Logger("bitswap")

21 22
// NetMessageSession initializes a BitSwap session that communicates over the
// provided NetMessage service
23
func NetMessageSession(parent context.Context, p peer.Peer,
24
	net inet.Network, srv inet.Service, directory bsnet.Routing,
25
	d ds.ThreadSafeDatastore, nice bool) exchange.Interface {
26

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
27
	networkAdapter := bsnet.NetMessageAdapter(srv, net, nil)
28 29 30
	bs := &bitswap{
		blockstore:    blockstore.NewBlockstore(d),
		notifications: notifications.New(),
31
		strategy:      strategy.New(nice),
32
		routing:       directory,
33
		sender:        networkAdapter,
34
		wantlist:      u.NewKeySet(),
35
	}
36
	networkAdapter.SetDelegate(bs)
37 38 39 40

	return bs
}

41 42
// bitswap instances implement the bitswap protocol.
type bitswap struct {
43

44
	// sender delivers messages on behalf of the session
45
	sender bsnet.Adapter
46

47
	// blockstore is the local database
48
	// NB: ensure threadsafety
49
	blockstore blockstore.Blockstore
50

51
	// routing interface for communication
52
	routing bsnet.Routing
53

54
	notifications notifications.PubSub
55

56
	// strategy listens to network traffic and makes decisions about how to
57
	// interact with partners.
58 59
	// TODO(brian): save the strategy's state to the datastore
	strategy strategy.Strategy
60

61
	wantlist u.KeySet
62 63
}

64 65
// GetBlock attempts to retrieve a particular block from peers within the
// deadline enforced by the context
66 67
//
// TODO ensure only one active request per key
68
func (bs *bitswap) Block(parent context.Context, k u.Key) (*blocks.Block, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
69
	log.Debug("Get Block %v", k)
70

71
	ctx, cancelFunc := context.WithCancel(parent)
72
	bs.wantlist.Add(k)
73
	promise := bs.notifications.Subscribe(ctx, k)
74

75 76
	const maxProviders = 20
	peersToQuery := bs.routing.FindProvidersAsync(ctx, k, maxProviders)
77

78
	go func() {
79
		message := bsmsg.New()
80 81 82
		for _, wanted := range bs.wantlist.Keys() {
			message.AppendWanted(wanted)
		}
83
		message.AppendWanted(k)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
84 85
		for peerToQuery := range peersToQuery {
			log.Debug("bitswap got peersToQuery: %s", peerToQuery)
86
			go func(p peer.Peer) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
87

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
88
				log.Debug("bitswap dialing peer: %s", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
89 90
				err := bs.sender.DialPeer(p)
				if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
91
					log.Errorf("Error sender.DialPeer(%s)", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
92 93 94
					return
				}

95
				response, err := bs.sender.SendRequest(ctx, p, message)
96
				if err != nil {
Jeromy's avatar
Jeromy committed
97
					log.Error("Error sender.SendRequest(%s) = %s", p, err)
98 99
					return
				}
100 101 102 103 104
				// FIXME ensure accounting is handled correctly when
				// communication fails. May require slightly different API to
				// get better guarantees. May need shared sequence numbers.
				bs.strategy.MessageSent(p, message)

105 106 107
				if response == nil {
					return
				}
108
				bs.ReceiveMessage(ctx, p, response)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109
			}(peerToQuery)
110 111
		}
	}()
112 113

	select {
114 115
	case block := <-promise:
		cancelFunc()
116
		bs.wantlist.Remove(k)
117
		// TODO remove from wantlist
118
		return &block, nil
119 120
	case <-parent.Done():
		return nil, parent.Err()
121 122 123
	}
}

124
// HasBlock announces the existance of a block to bitswap, potentially sending
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
125
// it to peers (Partners) whose WantLists include it.
126
func (bs *bitswap) HasBlock(ctx context.Context, blk blocks.Block) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
127
	log.Debug("Has Block %v", blk.Key())
128
	bs.wantlist.Remove(blk.Key())
129
	bs.sendToPeersThatWant(ctx, blk)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
130
	return bs.routing.Provide(ctx, blk.Key())
131 132
}

133
// TODO(brian): handle errors
134 135
func (bs *bitswap) ReceiveMessage(ctx context.Context, p peer.Peer, incoming bsmsg.BitSwapMessage) (
	peer.Peer, bsmsg.BitSwapMessage) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
136
	log.Debug("ReceiveMessage from %v", p.Key())
137

138
	if p == nil {
139 140
		// TODO propagate the error upward
		return nil, nil
141 142
	}
	if incoming == nil {
143 144
		// TODO propagate the error upward
		return nil, nil
145
	}
146

147
	bs.strategy.MessageReceived(p, incoming) // FIRST
148

149
	for _, block := range incoming.Blocks() {
150
		// TODO verify blocks?
151
		if err := bs.blockstore.Put(&block); err != nil {
152
			continue // FIXME(brian): err ignored
153
		}
154
		go bs.notifications.Publish(block)
155
		go func(block blocks.Block) {
156
			_ = bs.HasBlock(ctx, block) // FIXME err ignored
157
		}(block)
158 159
	}

160 161 162 163
	message := bsmsg.New()
	for _, wanted := range bs.wantlist.Keys() {
		message.AppendWanted(wanted)
	}
164 165
	for _, key := range incoming.Wantlist() {
		if bs.strategy.ShouldSendBlockToPeer(key, p) {
166 167 168 169
			if block, errBlockNotFound := bs.blockstore.Get(key); errBlockNotFound != nil {
				continue
			} else {
				message.AppendBlock(*block)
170
			}
171 172
		}
	}
173
	defer bs.strategy.MessageSent(p, message)
174 175 176 177 178 179
	return p, message
}

func (bs *bitswap) ReceiveError(err error) {
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
180
}
181

182 183
// send strives to ensure that accounting is always performed when a message is
// sent
184
func (bs *bitswap) send(ctx context.Context, p peer.Peer, m bsmsg.BitSwapMessage) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
185
	bs.sender.SendMessage(ctx, p, m)
186
	go bs.strategy.MessageSent(p, m)
187 188
}

189
func (bs *bitswap) sendToPeersThatWant(ctx context.Context, block blocks.Block) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
190
	log.Debug("Sending %v to peers that want it", block.Key())
191 192
	for _, p := range bs.strategy.Peers() {
		if bs.strategy.BlockIsWantedByPeer(block.Key(), p) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
193
			log.Debug("%v wants %v", p, block.Key())
194 195 196
			if bs.strategy.ShouldSendBlockToPeer(block.Key(), p) {
				message := bsmsg.New()
				message.AppendBlock(block)
197 198 199
				for _, wanted := range bs.wantlist.Keys() {
					message.AppendWanted(wanted)
				}
200
				go bs.send(ctx, p, message)
201 202 203 204
			}
		}
	}
}