bitswap.go 6.32 KB
Newer Older
1 2 3 4
package bitswap

import (
	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"
6 7 8 9 10 11 12 13

	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"
14
	inet "github.com/jbenet/go-ipfs/net"
15 16 17 18
	peer "github.com/jbenet/go-ipfs/peer"
	u "github.com/jbenet/go-ipfs/util"
)

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 43 44
// bitswap instances implement the bitswap protocol.
type bitswap struct {

	// sender delivers messages on behalf of the session
45
	sender bsnet.Adapter
46 47 48 49 50 51

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

	// routing interface for communication
52
	routing bsnet.Routing
53 54 55 56 57 58 59

	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
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) {
69
	log.Debugf("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
		for _, wanted := range bs.wantlist.Keys() {
81
			message.AddWanted(wanted)
82
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
83
		for peerToQuery := range peersToQuery {
84
			log.Debugf("bitswap got peersToQuery: %s", peerToQuery)
85
			go func(p peer.Peer) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
86

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

94
				response, err := bs.sender.SendRequest(ctx, p, message)
95
				if err != nil {
Jeromy's avatar
Jeromy committed
96
					log.Error("Error sender.SendRequest(%s) = %s", p, err)
97 98
					return
				}
99 100 101 102 103
				// 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)

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

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

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

// TODO(brian): handle errors
133 134
func (bs *bitswap) ReceiveMessage(ctx context.Context, p peer.Peer, incoming bsmsg.BitSwapMessage) (
	peer.Peer, bsmsg.BitSwapMessage) {
135 136
	log.Debugf("ReceiveMessage from %v", p.Key())
	log.Debugf("Message wantlist: %v", incoming.Wantlist())
137

138
	if p == nil {
139
		log.Error("Received message from nil peer!")
140 141
		// TODO propagate the error upward
		return nil, nil
142 143
	}
	if incoming == nil {
144
		log.Error("Got nil bitswap message!")
145 146
		// TODO propagate the error upward
		return nil, nil
147
	}
148

149 150 151
	// Record message bytes in ledger
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
152
	bs.strategy.MessageReceived(p, incoming) // FIRST
153

154
	for _, block := range incoming.Blocks() {
155
		// TODO verify blocks?
156
		if err := bs.blockstore.Put(&block); err != nil {
157
			continue // FIXME(brian): err ignored
158
		}
159
		go bs.notifications.Publish(block)
160
		go func(block blocks.Block) {
161 162 163 164
			err := bs.HasBlock(ctx, block) // FIXME err ignored
			if err != nil {
				log.Errorf("HasBlock errored: %s", err)
			}
165
		}(block)
166 167
	}

168 169
	message := bsmsg.New()
	for _, wanted := range bs.wantlist.Keys() {
170
		message.AddWanted(wanted)
171
	}
172
	for _, key := range incoming.Wantlist() {
173 174
		// TODO: might be better to check if we have the block before checking
		//			if we should send it to someone
175
		if bs.strategy.ShouldSendBlockToPeer(key, p) {
176 177 178
			if block, errBlockNotFound := bs.blockstore.Get(key); errBlockNotFound != nil {
				continue
			} else {
179
				message.AddBlock(*block)
180 181 182
			}
		}
	}
183
	defer bs.strategy.MessageSent(p, message)
184 185

	log.Debug("Returning message.")
186 187 188 189
	return p, message
}

func (bs *bitswap) ReceiveError(err error) {
190
	log.Errorf("Bitswap ReceiveError: %s", err)
191 192
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
193 194
}

195 196
// send strives to ensure that accounting is always performed when a message is
// sent
197
func (bs *bitswap) send(ctx context.Context, p peer.Peer, m bsmsg.BitSwapMessage) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
198
	bs.sender.SendMessage(ctx, p, m)
199
	go bs.strategy.MessageSent(p, m)
200 201
}

202
func (bs *bitswap) sendToPeersThatWant(ctx context.Context, block blocks.Block) {
203
	log.Debugf("Sending %v to peers that want it", block.Key())
204 205
	for _, p := range bs.strategy.Peers() {
		if bs.strategy.BlockIsWantedByPeer(block.Key(), p) {
206
			log.Debugf("%v wants %v", p, block.Key())
207 208
			if bs.strategy.ShouldSendBlockToPeer(block.Key(), p) {
				message := bsmsg.New()
209
				message.AddBlock(block)
210
				for _, wanted := range bs.wantlist.Keys() {
211
					message.AddWanted(wanted)
212
				}
213
				go bs.send(ctx, p, message)
214 215 216 217
			}
		}
	}
}