bitswap.go 6.49 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 18 19 20 21

	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"
	peer "github.com/jbenet/go-ipfs/peer"
	u "github.com/jbenet/go-ipfs/util"
)

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

24 25 26
// New initializes a BitSwap instance that communicates over the
// provided BitSwapNetwork. This function registers the returned instance as
// the network delegate.
27
// Runs until context is cancelled
28 29
func New(ctx context.Context, p peer.Peer,
	network bsnet.BitSwapNetwork, 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
		}
	}()

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

	return bs
}

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

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

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

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

	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
72

73
	wantlist u.KeySet
74 75
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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