bitswap.go 6.54 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.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
10

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

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

32 33
	notif := notifications.New()
	go func() {
34 35 36
		select {
		case <-ctx.Done():
			notif.Shutdown()
37 38 39
		}
	}()

Brian Tiger Chow's avatar
Brian Tiger Chow committed
40 41
	network := bsnet.NetMessageAdapter(srv, net, nil)

42 43
	bs := &bitswap{
		blockstore:    blockstore.NewBlockstore(d),
44
		notifications: notif,
45
		strategy:      strategy.New(nice),
46
		routing:       routing,
Brian Tiger Chow's avatar
Brian Tiger Chow committed
47
		sender:        network,
48
		wantlist:      u.NewKeySet(),
49
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
50
	network.SetDelegate(bs)
51 52 53 54

	return bs
}

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

58
	// sender delivers messages on behalf of the session
59
	sender bsnet.BitSwapNetwork
60

61
	// blockstore is the local database
62
	// NB: ensure threadsafety
63
	blockstore blockstore.Blockstore
64

65
	// routing interface for communication
66
	routing bsnet.Routing
67

68
	notifications notifications.PubSub
69

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

75
	wantlist u.KeySet
76 77
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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