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

import (
Jeromy's avatar
Jeromy committed
4 5
	"time"

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9
	blocks "github.com/jbenet/go-ipfs/blocks"
10
	blockstore "github.com/jbenet/go-ipfs/blockstore"
11 12 13 14 15
	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"
16
	inet "github.com/jbenet/go-ipfs/net"
17
	peer "github.com/jbenet/go-ipfs/peer"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18
	u "github.com/jbenet/go-ipfs/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
19 20
)

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

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

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

	return bs
}

43 44
// bitswap instances implement the bitswap protocol.
type bitswap struct {
45

46
	// sender delivers messages on behalf of the session
47
	sender bsnet.Adapter
48

49
	// blockstore is the local database
50
	// NB: ensure threadsafety
51
	blockstore blockstore.Blockstore
52

53
	// routing interface for communication
54
	routing bsnet.Routing
55

56
	notifications notifications.PubSub
57

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

63
	wantlist u.KeySet
64 65
}

66 67
// GetBlock attempts to retrieve a particular block from peers within the
// deadline enforced by the context
68 69
//
// TODO ensure only one active request per key
70
func (bs *bitswap) Block(parent context.Context, k u.Key) (*blocks.Block, error) {
71
	log.Debugf("Get Block %v", k)
Jeromy's avatar
Jeromy committed
72 73 74 75
	now := time.Now()
	defer func() {
		log.Errorf("GetBlock took %f secs", time.Now().Sub(now).Seconds())
	}()
76

77
	ctx, cancelFunc := context.WithCancel(parent)
78
	bs.wantlist.Add(k)
79
	promise := bs.notifications.Subscribe(ctx, k)
80

81 82
	const maxProviders = 20
	peersToQuery := bs.routing.FindProvidersAsync(ctx, k, maxProviders)
83

84
	go func() {
85
		message := bsmsg.New()
86
		for _, wanted := range bs.wantlist.Keys() {
87
			message.AddWanted(wanted)
88
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
89
		for peerToQuery := range peersToQuery {
90
			log.Debugf("bitswap got peersToQuery: %s", peerToQuery)
91
			go func(p peer.Peer) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
92

93
				log.Debugf("bitswap dialing peer: %s", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
94 95
				err := bs.sender.DialPeer(p)
				if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
96
					log.Errorf("Error sender.DialPeer(%s)", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
97 98 99
					return
				}

100
				response, err := bs.sender.SendRequest(ctx, p, message)
101
				if err != nil {
Jeromy's avatar
Jeromy committed
102
					log.Error("Error sender.SendRequest(%s) = %s", p, err)
103 104
					return
				}
105 106 107 108 109
				// 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)

110 111 112
				if response == nil {
					return
				}
113
				bs.ReceiveMessage(ctx, p, response)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
114
			}(peerToQuery)
115 116
		}
	}()
117 118

	select {
119 120
	case block := <-promise:
		cancelFunc()
121
		bs.wantlist.Remove(k)
122
		// TODO remove from wantlist
123
		return &block, nil
124 125
	case <-parent.Done():
		return nil, parent.Err()
126 127 128
	}
}

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

138
// TODO(brian): handle errors
139 140
func (bs *bitswap) ReceiveMessage(ctx context.Context, p peer.Peer, incoming bsmsg.BitSwapMessage) (
	peer.Peer, bsmsg.BitSwapMessage) {
141 142
	log.Debugf("ReceiveMessage from %v", p.Key())
	log.Debugf("Message wantlist: %v", incoming.Wantlist())
143

144
	if p == nil {
145
		log.Error("Received message from nil peer!")
146 147
		// TODO propagate the error upward
		return nil, nil
148 149
	}
	if incoming == nil {
150
		log.Error("Got nil bitswap message!")
151 152
		// TODO propagate the error upward
		return nil, nil
153
	}
154

155 156 157
	// Record message bytes in ledger
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
158
	bs.strategy.MessageReceived(p, incoming) // FIRST
159

160
	for _, block := range incoming.Blocks() {
161
		// TODO verify blocks?
162
		if err := bs.blockstore.Put(&block); err != nil {
163
			continue // FIXME(brian): err ignored
164
		}
165
		go bs.notifications.Publish(block)
166
		go func(block blocks.Block) {
167 168
			err := bs.HasBlock(ctx, block) // FIXME err ignored
			if err != nil {
Jeromy's avatar
Jeromy committed
169
				log.Warningf("HasBlock errored: %s", err)
170
			}
171
		}(block)
172 173
	}

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

	log.Debug("Returning message.")
192 193 194 195
	return p, message
}

func (bs *bitswap) ReceiveError(err error) {
196
	log.Errorf("Bitswap ReceiveError: %s", err)
197 198
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
199
}
200

201 202
// send strives to ensure that accounting is always performed when a message is
// sent
203
func (bs *bitswap) send(ctx context.Context, p peer.Peer, m bsmsg.BitSwapMessage) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
204
	bs.sender.SendMessage(ctx, p, m)
205
	go bs.strategy.MessageSent(p, m)
206 207
}

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