bitswap.go 6.56 KB
Newer Older
Brian Tiger Chow's avatar
Brian Tiger Chow committed
1 2
// package bitswap implements the IPFS Exchange interface with the BitSwap
// bilateral exchange protocol.
3 4 5
package bitswap

import (
Jeromy's avatar
Jeromy committed
6 7
	"time"

8
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
9
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
10 11 12 13 14 15 16 17

	blocks "github.com/jbenet/go-ipfs/blocks"
	blockstore "github.com/jbenet/go-ipfs/blockstore"
	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"
18
	inet "github.com/jbenet/go-ipfs/net"
19 20 21 22
	peer "github.com/jbenet/go-ipfs/peer"
	u "github.com/jbenet/go-ipfs/util"
)

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

25
// NetMessageSession initializes a BitSwap session that communicates over the
26 27 28
// provided NetMessage service.
// Runs until context is cancelled
func NetMessageSession(ctx context.Context, p peer.Peer,
29
	net inet.Network, srv inet.Service, routing bsnet.Routing,
30
	d ds.ThreadSafeDatastore, nice bool) exchange.Interface {
31

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
32
	networkAdapter := bsnet.NetMessageAdapter(srv, net, nil)
33 34 35 36

	notif := notifications.New()

	go func() {
37 38 39
		select {
		case <-ctx.Done():
			notif.Shutdown()
40 41 42
		}
	}()

43 44
	bs := &bitswap{
		blockstore:    blockstore.NewBlockstore(d),
45
		notifications: notif,
46
		strategy:      strategy.New(nice),
47
		routing:       routing,
48
		sender:        networkAdapter,
49
		wantlist:      u.NewKeySet(),
50
	}
51
	networkAdapter.SetDelegate(bs)
52 53 54 55

	return bs
}

56 57 58 59
// bitswap instances implement the bitswap protocol.
type bitswap struct {

	// sender delivers messages on behalf of the session
60
	sender bsnet.BitSwapNetwork
61 62 63 64 65 66

	// blockstore is the local database
	// NB: ensure threadsafety
	blockstore blockstore.Blockstore

	// routing interface for communication
67
	routing bsnet.Routing
68 69 70 71 72 73 74

	notifications notifications.PubSub

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

76
	wantlist u.KeySet
77 78
}

79 80
// GetBlock attempts to retrieve a particular block from peers within the
// deadline enforced by the context
81 82
//
// TODO ensure only one active request per key
83
func (bs *bitswap) Block(parent context.Context, k u.Key) (*blocks.Block, error) {
84
	log.Debugf("Get Block %v", k)
Jeromy's avatar
Jeromy committed
85 86
	now := time.Now()
	defer func() {
87
		log.Debugf("GetBlock took %f secs", time.Now().Sub(now).Seconds())
Jeromy's avatar
Jeromy committed
88
	}()
89

90
	ctx, cancelFunc := context.WithCancel(parent)
91 92
	defer cancelFunc()

93
	bs.wantlist.Add(k)
94
	promise := bs.notifications.Subscribe(ctx, k)
95

96 97
	const maxProviders = 20
	peersToQuery := bs.routing.FindProvidersAsync(ctx, k, maxProviders)
98

99
	go func() {
100
		message := bsmsg.New()
101
		for _, wanted := range bs.wantlist.Keys() {
102
			message.AddWanted(wanted)
103
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
104
		for peerToQuery := range peersToQuery {
105
			log.Debugf("bitswap got peersToQuery: %s", peerToQuery)
106
			go func(p peer.Peer) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
107

108
				log.Debugf("bitswap dialing peer: %s", p)
109
				err := bs.sender.DialPeer(ctx, p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
110
				if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
111
					log.Errorf("Error sender.DialPeer(%s)", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
112 113 114
					return
				}

115
				response, err := bs.sender.SendRequest(ctx, p, message)
116
				if err != nil {
Jeromy's avatar
Jeromy committed
117
					log.Errorf("Error sender.SendRequest(%s) = %s", p, err)
118 119
					return
				}
120 121 122 123 124
				// 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)

125 126 127
				if response == nil {
					return
				}
128
				bs.ReceiveMessage(ctx, p, response)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129
			}(peerToQuery)
130 131 132 133
		}
	}()

	select {
134
	case block := <-promise:
135
		bs.wantlist.Remove(k)
136
		return &block, nil
137 138
	case <-parent.Done():
		return nil, parent.Err()
139 140 141
	}
}

142 143
// HasBlock announces the existance of a block to this bitswap service. The
// service will potentially notify its peers.
144
func (bs *bitswap) HasBlock(ctx context.Context, blk blocks.Block) error {
145
	log.Debugf("Has Block %v", blk.Key())
146
	bs.wantlist.Remove(blk.Key())
147
	bs.sendToPeersThatWant(ctx, blk)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148
	return bs.routing.Provide(ctx, blk.Key())
149 150 151
}

// TODO(brian): handle errors
152 153
func (bs *bitswap) ReceiveMessage(ctx context.Context, p peer.Peer, incoming bsmsg.BitSwapMessage) (
	peer.Peer, bsmsg.BitSwapMessage) {
154 155
	log.Debugf("ReceiveMessage from %v", p.Key())
	log.Debugf("Message wantlist: %v", incoming.Wantlist())
156

157
	if p == nil {
158
		log.Error("Received message from nil peer!")
159 160
		// TODO propagate the error upward
		return nil, nil
161 162
	}
	if incoming == nil {
163
		log.Error("Got nil bitswap message!")
164 165
		// TODO propagate the error upward
		return nil, nil
166
	}
167

168 169 170
	// Record message bytes in ledger
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
171
	bs.strategy.MessageReceived(p, incoming) // FIRST
172

173
	for _, block := range incoming.Blocks() {
174
		// TODO verify blocks?
175
		if err := bs.blockstore.Put(&block); err != nil {
176
			continue // FIXME(brian): err ignored
177
		}
178 179 180 181 182
		bs.notifications.Publish(block)
		err := bs.HasBlock(ctx, block)
		if err != nil {
			log.Warningf("HasBlock errored: %s", err)
		}
183 184
	}

185 186
	message := bsmsg.New()
	for _, wanted := range bs.wantlist.Keys() {
187
		message.AddWanted(wanted)
188
	}
189
	for _, key := range incoming.Wantlist() {
190 191
		// TODO: might be better to check if we have the block before checking
		//			if we should send it to someone
192
		if bs.strategy.ShouldSendBlockToPeer(key, p) {
193 194 195
			if block, errBlockNotFound := bs.blockstore.Get(key); errBlockNotFound != nil {
				continue
			} else {
196
				message.AddBlock(*block)
197 198 199
			}
		}
	}
200
	defer bs.strategy.MessageSent(p, message)
201 202

	log.Debug("Returning message.")
203 204 205 206
	return p, message
}

func (bs *bitswap) ReceiveError(err error) {
207
	log.Errorf("Bitswap ReceiveError: %s", err)
208 209
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
210 211
}

212 213
// send strives to ensure that accounting is always performed when a message is
// sent
214
func (bs *bitswap) send(ctx context.Context, p peer.Peer, m bsmsg.BitSwapMessage) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
215
	bs.sender.SendMessage(ctx, p, m)
216
	bs.strategy.MessageSent(p, m)
217 218
}

219
func (bs *bitswap) sendToPeersThatWant(ctx context.Context, block blocks.Block) {
220
	log.Debugf("Sending %v to peers that want it", block.Key())
221

222 223
	for _, p := range bs.strategy.Peers() {
		if bs.strategy.BlockIsWantedByPeer(block.Key(), p) {
224
			log.Debugf("%v wants %v", p, block.Key())
225 226
			if bs.strategy.ShouldSendBlockToPeer(block.Key(), p) {
				message := bsmsg.New()
227
				message.AddBlock(block)
228
				for _, wanted := range bs.wantlist.Keys() {
229
					message.AddWanted(wanted)
230
				}
231
				bs.send(ctx, p, message)
232 233 234 235
			}
		}
	}
}