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

import (
Jeromy's avatar
Jeromy committed
4 5
	"time"

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

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

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

23
// NetMessageSession initializes a BitSwap session that communicates over the
24 25 26
// provided NetMessage service.
// Runs until context is cancelled
func NetMessageSession(ctx context.Context, p peer.Peer,
27
	net inet.Network, srv inet.Service, directory bsnet.Routing,
28
	d ds.ThreadSafeDatastore, nice bool) exchange.Interface {
29

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
30
	networkAdapter := bsnet.NetMessageAdapter(srv, net, nil)
31 32 33 34 35 36 37 38 39 40 41 42

	notif := notifications.New()

	go func() {
		for {
			select {
			case <-ctx.Done():
				notif.Shutdown()
			}
		}
	}()

43 44
	bs := &bitswap{
		blockstore:    blockstore.NewBlockstore(d),
45
		notifications: notif,
46
		strategy:      strategy.New(nice),
47
		routing:       directory,
48
		sender:        networkAdapter,
49
		wantlist:      u.NewKeySet(),
50
	}
51
	networkAdapter.SetDelegate(bs)
52 53 54 55

	return bs
}

56 57
// bitswap instances implement the bitswap protocol.
type bitswap struct {
58

59
	// sender delivers messages on behalf of the session
60
	sender bsnet.Adapter
61

62
	// blockstore is the local database
63
	// NB: ensure threadsafety
64
	blockstore blockstore.Blockstore
65

66
	// routing interface for communication
67
	routing bsnet.Routing
68

69
	notifications notifications.PubSub
70

71
	// strategy listens to network traffic and makes decisions about how to
72
	// interact with partners.
73 74
	// TODO(brian): save the strategy's state to the datastore
	strategy strategy.Strategy
75

76
	wantlist u.KeySet
77 78
}

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

90
	ctx, cancelFunc := context.WithCancel(parent)
91
	bs.wantlist.Add(k)
92
	promise := bs.notifications.Subscribe(ctx, k)
93

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

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

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

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

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

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

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

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

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

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

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

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

	log.Debug("Returning message.")
202 203 204 205
	return p, message
}

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

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

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

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