bitswap.go 5.49 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
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"
	peer "github.com/jbenet/go-ipfs/peer"
	u "github.com/jbenet/go-ipfs/util"
)

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

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

	return bs
}

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

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

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

	// routing interface for communication
47
	routing bsnet.Routing
48 49 50 51 52 53 54

	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
55

56
	wantlist u.KeySet
57 58
}

59 60
// GetBlock attempts to retrieve a particular block from peers within the
// deadline enforced by the context
61 62
//
// TODO ensure only one active request per key
63
func (bs *bitswap) Block(parent context.Context, k u.Key) (*blocks.Block, error) {
64
	u.DOut("Get Block %v\n", k)
65

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

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

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

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

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

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

// TODO(brian): handle errors
120
func (bs *bitswap) ReceiveMessage(ctx context.Context, p *peer.Peer, incoming bsmsg.BitSwapMessage) (
121
	*peer.Peer, bsmsg.BitSwapMessage) {
122
	u.DOut("ReceiveMessage from %v\n", p.Key())
123

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

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

135
	for _, block := range incoming.Blocks() {
136
		// TODO verify blocks?
137
		if err := bs.blockstore.Put(&block); err != nil {
138
			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
	defer bs.strategy.MessageSent(p, message)
160 161 162 163 164 165
	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
166 167
}

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

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