bitswap.go 5.42 KB
Newer Older
1 2 3
package bitswap

import (
4 5
	"errors"

6 7 8 9 10 11 12 13 14 15 16 17 18 19
	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"
	peer "github.com/jbenet/go-ipfs/peer"
	u "github.com/jbenet/go-ipfs/util"
)

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 40 41
// bitswap instances implement the bitswap protocol.
type bitswap struct {

	// sender delivers messages on behalf of the session
42
	sender bsnet.Adapter
43 44 45 46 47 48

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

	// routing interface for communication
49
	routing bsnet.Routing
50 51 52 53 54 55 56

	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
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) {
66
	u.DOut("Get Block %v\n", k.Pretty())
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 {
82
			// u.DOut("bitswap got peersToQuery: %s\n", 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 113
	}
}

// HasBlock announces the existance of a block to bitswap, potentially sending
// it to peers (Partners) whose WantLists include it.
114
func (bs *bitswap) HasBlock(ctx context.Context, blk blocks.Block) error {
115 116
	u.DOut("Has Block %v\n", blk.Key().Pretty())
	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, error) {
124
	u.DOut("ReceiveMessage from %v\n", p.Key().Pretty())
125

126 127 128 129 130 131
	if p == nil {
		return nil, nil, errors.New("Received nil Peer")
	}
	if incoming == nil {
		return nil, nil, errors.New("Received nil Message")
	}
132

133
	bs.strategy.MessageReceived(p, incoming) // FIRST
134

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

146 147 148 149
	message := bsmsg.New()
	for _, wanted := range bs.wantlist.Keys() {
		message.AppendWanted(wanted)
	}
150 151
	for _, key := range incoming.Wantlist() {
		if bs.strategy.ShouldSendBlockToPeer(key, p) {
152 153 154 155
			if block, errBlockNotFound := bs.blockstore.Get(key); errBlockNotFound != nil {
				continue
			} else {
				message.AppendBlock(*block)
156 157 158
			}
		}
	}
159 160
	defer bs.strategy.MessageSent(p, message)
	return p, message, nil
161 162
}

163 164 165
// 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
166
	bs.sender.SendMessage(ctx, p, m)
167
	go bs.strategy.MessageSent(p, m)
168 169
}

170
func (bs *bitswap) sendToPeersThatWant(ctx context.Context, block blocks.Block) {
171
	u.DOut("Sending %v to peers that want it\n", block.Key().Pretty())
172 173
	for _, p := range bs.strategy.Peers() {
		if bs.strategy.BlockIsWantedByPeer(block.Key(), p) {
174
			u.DOut("%v wants %v\n", p.Key().Pretty(), block.Key().Pretty())
175 176 177
			if bs.strategy.ShouldSendBlockToPeer(block.Key(), p) {
				message := bsmsg.New()
				message.AppendBlock(block)
178 179 180
				for _, wanted := range bs.wantlist.Keys() {
					message.AppendWanted(wanted)
				}
181
				go bs.send(ctx, p, message)
182 183 184 185
			}
		}
	}
}