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

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

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

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

20 21
// NetMessageSession initializes a BitSwap session that communicates over the
// provided NetMessage service
22
func NetMessageSession(parent context.Context, p *peer.Peer, s bsnet.NetMessageService, directory bsnet.Routing, d ds.Datastore, nice bool) exchange.Interface {
23

24
	networkAdapter := bsnet.NetMessageAdapter(s, nil)
25 26 27
	bs := &bitswap{
		blockstore:    blockstore.NewBlockstore(d),
		notifications: notifications.New(),
28
		strategy:      strategy.New(nice),
29
		routing:       directory,
30
		sender:        networkAdapter,
31
		wantlist:      u.NewKeySet(),
32
	}
33
	networkAdapter.SetDelegate(bs)
34 35 36 37

	return bs
}

38 39
// bitswap instances implement the bitswap protocol.
type bitswap struct {
40

41
	// sender delivers messages on behalf of the session
42
	sender bsnet.Adapter
43

44
	// blockstore is the local database
45
	// NB: ensure threadsafety
46
	blockstore blockstore.Blockstore
47

48
	// routing interface for communication
49
	routing bsnet.Routing
50

51
	notifications notifications.PubSub
52

53
	// strategy listens to network traffic and makes decisions about how to
54
	// interact with partners.
55 56
	// TODO(brian): save the strategy's state to the datastore
	strategy strategy.Strategy
57

58
	wantlist u.KeySet
59 60
}

61 62
// GetBlock attempts to retrieve a particular block from peers within the
// deadline enforced by the context
63 64
//
// TODO ensure only one active request per key
65
func (bs *bitswap) Block(parent context.Context, k u.Key) (*blocks.Block, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
66
	log.Debug("Get Block %v", k)
67

68
	ctx, cancelFunc := context.WithCancel(parent)
69
	bs.wantlist.Add(k)
70
	promise := bs.notifications.Subscribe(ctx, k)
71

72 73
	const maxProviders = 20
	peersToQuery := bs.routing.FindProvidersAsync(ctx, k, maxProviders)
74

75
	go func() {
76
		message := bsmsg.New()
77 78 79
		for _, wanted := range bs.wantlist.Keys() {
			message.AppendWanted(wanted)
		}
80
		message.AppendWanted(k)
81
		for iiiii := range peersToQuery {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
82
			// log.Debug("bitswap got peersToQuery: %s", iiiii)
83
			go func(p *peer.Peer) {
84
				response, err := bs.sender.SendRequest(ctx, p, message)
85 86 87
				if err != nil {
					return
				}
88 89 90 91 92
				// 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)

93 94 95
				if response == nil {
					return
				}
96
				bs.ReceiveMessage(ctx, p, response)
97
			}(iiiii)
98 99
		}
	}()
100 101

	select {
102 103
	case block := <-promise:
		cancelFunc()
104
		bs.wantlist.Remove(k)
105
		// TODO remove from wantlist
106
		return &block, nil
107 108
	case <-parent.Done():
		return nil, parent.Err()
109 110 111
	}
}

112
// HasBlock announces the existance of a block to bitswap, potentially sending
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
113
// it to peers (Partners) whose WantLists include it.
114
func (bs *bitswap) HasBlock(ctx context.Context, blk blocks.Block) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
115
	log.Debug("Has Block %v", blk.Key())
116
	bs.wantlist.Remove(blk.Key())
117
	bs.sendToPeersThatWant(ctx, blk)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
118
	return bs.routing.Provide(ctx, blk.Key())
119 120
}

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

126
	if p == nil {
127 128
		// TODO propagate the error upward
		return nil, nil
129 130
	}
	if incoming == nil {
131 132
		// TODO propagate the error upward
		return nil, nil
133
	}
134

135
	bs.strategy.MessageReceived(p, incoming) // FIRST
136

137
	for _, block := range incoming.Blocks() {
138
		// TODO verify blocks?
139
		if err := bs.blockstore.Put(&block); err != nil {
140
			continue // FIXME(brian): err ignored
141
		}
142
		go bs.notifications.Publish(block)
143
		go func(block blocks.Block) {
144
			_ = bs.HasBlock(ctx, block) // FIXME err ignored
145
		}(block)
146 147
	}

148 149 150 151
	message := bsmsg.New()
	for _, wanted := range bs.wantlist.Keys() {
		message.AppendWanted(wanted)
	}
152 153
	for _, key := range incoming.Wantlist() {
		if bs.strategy.ShouldSendBlockToPeer(key, p) {
154 155 156 157
			if block, errBlockNotFound := bs.blockstore.Get(key); errBlockNotFound != nil {
				continue
			} else {
				message.AppendBlock(*block)
158
			}
159 160
		}
	}
161
	defer bs.strategy.MessageSent(p, message)
162 163 164 165 166 167
	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
168
}
169

170 171 172
// 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
173
	bs.sender.SendMessage(ctx, p, m)
174
	go bs.strategy.MessageSent(p, m)
175 176
}

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