bitswap.go 5.67 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
package bitswap

import (
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/datastore.go"

	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 24 25
func NetMessageSession(parent context.Context, p *peer.Peer,
	net inet.Network, srv inet.Service, directory bsnet.Routing,
	d ds.Datastore, nice bool) exchange.Interface {
26

27
	networkAdapter := bsnet.NetMessageAdapter(srv, nil)
28 29 30
	bs := &bitswap{
		blockstore:    blockstore.NewBlockstore(d),
		notifications: notifications.New(),
31
		strategy:      strategy.New(nice),
32
		routing:       directory,
33
		network:       net,
34
		sender:        networkAdapter,
35
		wantlist:      u.NewKeySet(),
36
	}
37
	networkAdapter.SetDelegate(bs)
38 39 40 41

	return bs
}

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

45 46 47
	// network maintains connections to the outside world.
	network inet.Network

48
	// sender delivers messages on behalf of the session
49
	sender bsnet.Adapter
50 51 52 53 54 55

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

	// routing interface for communication
56
	routing bsnet.Routing
57 58 59 60 61 62 63

	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
64

65
	wantlist u.KeySet
66 67
}

68 69
// GetBlock attempts to retrieve a particular block from peers within the
// deadline enforced by the context
70 71
//
// TODO ensure only one active request per key
72
func (bs *bitswap) Block(parent context.Context, k u.Key) (*blocks.Block, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
73
	log.Debug("Get Block %v", k)
74

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

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

82
	go func() {
83
		message := bsmsg.New()
84 85 86
		for _, wanted := range bs.wantlist.Keys() {
			message.AppendWanted(wanted)
		}
87
		message.AppendWanted(k)
88
		for iiiii := range peersToQuery {
89
			log.Debug("bitswap got peersToQuery: %s", iiiii)
90
			go func(p *peer.Peer) {
91
				response, err := bs.sender.SendRequest(ctx, p, message)
92 93 94
				if err != nil {
					return
				}
95 96 97 98 99
				// 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)

100 101 102
				if response == nil {
					return
				}
103
				bs.ReceiveMessage(ctx, p, response)
104
			}(iiiii)
105 106 107 108
		}
	}()

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

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

// TODO(brian): handle errors
129
func (bs *bitswap) ReceiveMessage(ctx context.Context, p *peer.Peer, incoming bsmsg.BitSwapMessage) (
130
	*peer.Peer, bsmsg.BitSwapMessage) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
131
	log.Debug("ReceiveMessage from %v", p.Key())
132

133
	if p == nil {
134 135
		// TODO propagate the error upward
		return nil, nil
136 137
	}
	if incoming == nil {
138 139
		// TODO propagate the error upward
		return nil, nil
140
	}
141

142
	bs.strategy.MessageReceived(p, incoming) // FIRST
143

144
	for _, block := range incoming.Blocks() {
145
		// TODO verify blocks?
146
		if err := bs.blockstore.Put(&block); err != nil {
147
			continue // FIXME(brian): err ignored
148
		}
149
		go bs.notifications.Publish(block)
150
		go func(block blocks.Block) {
151
			_ = bs.HasBlock(ctx, block) // FIXME err ignored
152
		}(block)
153 154
	}

155 156 157 158
	message := bsmsg.New()
	for _, wanted := range bs.wantlist.Keys() {
		message.AppendWanted(wanted)
	}
159 160
	for _, key := range incoming.Wantlist() {
		if bs.strategy.ShouldSendBlockToPeer(key, p) {
161 162 163 164
			if block, errBlockNotFound := bs.blockstore.Get(key); errBlockNotFound != nil {
				continue
			} else {
				message.AppendBlock(*block)
165 166 167
			}
		}
	}
168
	defer bs.strategy.MessageSent(p, message)
169 170 171 172 173 174
	return p, message
}

func (bs *bitswap) ReceiveError(err error) {
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
175 176
}

177 178 179
// send strives to ensure that accounting is always performed when a message is
// sent
func (bs *bitswap) send(ctx context.Context, p *peer.Peer, m bsmsg.BitSwapMessage) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
180
	bs.sender.SendMessage(ctx, p, m)
181
	go bs.strategy.MessageSent(p, m)
182 183
}

184
func (bs *bitswap) sendToPeersThatWant(ctx context.Context, block blocks.Block) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
185
	log.Debug("Sending %v to peers that want it", block.Key())
186 187
	for _, p := range bs.strategy.Peers() {
		if bs.strategy.BlockIsWantedByPeer(block.Key(), p) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
188
			log.Debug("%v wants %v", p, block.Key())
189 190 191
			if bs.strategy.ShouldSendBlockToPeer(block.Key(), p) {
				message := bsmsg.New()
				message.AppendBlock(block)
192 193 194
				for _, wanted := range bs.wantlist.Keys() {
					message.AppendWanted(wanted)
				}
195
				go bs.send(ctx, p, message)
196 197 198 199
			}
		}
	}
}