bitswap.go 6.46 KB
Newer Older
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"
8 9 10 11 12 13 14 15

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

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

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

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

	notif := notifications.New()

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

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

	return bs
}

54 55 56 57
// bitswap instances implement the bitswap protocol.
type bitswap struct {

	// sender delivers messages on behalf of the session
58
	sender bsnet.Adapter
59 60 61 62 63 64

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

	// routing interface for communication
65
	routing bsnet.Routing
66 67 68 69 70 71 72

	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
73

74
	wantlist u.KeySet
75 76
}

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

88
	ctx, cancelFunc := context.WithCancel(parent)
89 90
	defer cancelFunc()

91
	bs.wantlist.Add(k)
92
	promise := bs.notifications.Subscribe(ctx, k)
93

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

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

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

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

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

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

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

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

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

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

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

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

	log.Debug("Returning message.")
201 202 203 204
	return p, message
}

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

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

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

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