wantmanager.go 6.33 KB
Newer Older
1 2 3 4
package bitswap

import (
	"sync"
5
	"time"
6

7
	key "github.com/ipfs/go-ipfs/blocks/key"
8 9 10
	engine "github.com/ipfs/go-ipfs/exchange/bitswap/decision"
	bsmsg "github.com/ipfs/go-ipfs/exchange/bitswap/message"
	bsnet "github.com/ipfs/go-ipfs/exchange/bitswap/network"
11
	wantlist "github.com/ipfs/go-ipfs/exchange/bitswap/wantlist"
12
	peer "gx/ipfs/QmZwZjMVGss5rqYsJVGy18gNbkTJffFyq2x1uJ4e4p3ZAt/go-libp2p-peer"
Jeromy's avatar
Jeromy committed
13
	context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
14 15
)

16
type WantManager struct {
Jeromy's avatar
Jeromy committed
17 18
	// sync channels for Run loop
	incoming   chan []*bsmsg.Entry
19 20 21
	connect    chan peer.ID        // notification channel for new peers connecting
	disconnect chan peer.ID        // notification channel for peers disconnecting
	peerReqs   chan chan []peer.ID // channel to request connected peers on
22

Jeromy's avatar
Jeromy committed
23
	// synchronized by Run loop, only touch inside there
24
	peers map[peer.ID]*msgQueue
25
	wl    *wantlist.ThreadSafe
26

27
	network bsnet.BitSwapNetwork
Jeromy's avatar
Jeromy committed
28
	ctx     context.Context
29 30
}

31
func NewWantManager(ctx context.Context, network bsnet.BitSwapNetwork) *WantManager {
32 33
	return &WantManager{
		incoming:   make(chan []*bsmsg.Entry, 10),
34 35
		connect:    make(chan peer.ID, 10),
		disconnect: make(chan peer.ID, 10),
36
		peerReqs:   make(chan chan []peer.ID),
37
		peers:      make(map[peer.ID]*msgQueue),
38
		wl:         wantlist.NewThreadSafe(),
39
		network:    network,
40
		ctx:        ctx,
41 42 43 44 45 46 47 48 49 50
	}
}

type msgPair struct {
	to  peer.ID
	msg bsmsg.BitSwapMessage
}

type cancellation struct {
	who peer.ID
51
	blk key.Key
52 53 54 55 56
}

type msgQueue struct {
	p peer.ID

Jeromy's avatar
Jeromy committed
57 58 59
	outlk   sync.Mutex
	out     bsmsg.BitSwapMessage
	network bsnet.BitSwapNetwork
60

Jeromy's avatar
Jeromy committed
61 62
	refcnt int

63 64 65 66
	work chan struct{}
	done chan struct{}
}

67
func (pm *WantManager) WantBlocks(ks []key.Key) {
Jeromy's avatar
Jeromy committed
68
	log.Infof("want blocks: %s", ks)
69 70 71
	pm.addEntries(ks, false)
}

72
func (pm *WantManager) CancelWants(ks []key.Key) {
73 74 75
	pm.addEntries(ks, true)
}

76
func (pm *WantManager) addEntries(ks []key.Key, cancel bool) {
77 78 79 80 81 82 83 84 85 86
	var entries []*bsmsg.Entry
	for i, k := range ks {
		entries = append(entries, &bsmsg.Entry{
			Cancel: cancel,
			Entry: wantlist.Entry{
				Key:      k,
				Priority: kMaxPriority - i,
			},
		})
	}
87 88 89 90
	select {
	case pm.incoming <- entries:
	case <-pm.ctx.Done():
	}
91 92
}

93 94 95 96 97 98
func (pm *WantManager) ConnectedPeers() []peer.ID {
	resp := make(chan []peer.ID)
	pm.peerReqs <- resp
	return <-resp
}

99
func (pm *WantManager) SendBlock(ctx context.Context, env *engine.Envelope) {
100 101 102 103
	// Blocks need to be sent synchronously to maintain proper backpressure
	// throughout the network stack
	defer env.Sent()

104
	msg := bsmsg.New(false)
105
	msg.AddBlock(env.Block)
Jeromy's avatar
Jeromy committed
106
	log.Infof("Sending block %s to %s", env.Peer, env.Block)
Jeromy's avatar
Jeromy committed
107
	err := pm.network.SendMessage(ctx, env.Peer, msg)
108
	if err != nil {
rht's avatar
rht committed
109
		log.Infof("sendblock error: %s", err)
110 111 112
	}
}

113
func (pm *WantManager) startPeerHandler(p peer.ID) *msgQueue {
Jeromy's avatar
Jeromy committed
114
	mq, ok := pm.peers[p]
115
	if ok {
Jeromy's avatar
Jeromy committed
116
		mq.refcnt++
Jeromy's avatar
Jeromy committed
117
		return nil
118 119
	}

Jeromy's avatar
Jeromy committed
120
	mq = pm.newMsgQueue(p)
121 122

	// new peer, we will want to give them our full wantlist
123
	fullwantlist := bsmsg.New(true)
124 125 126 127 128
	for _, e := range pm.wl.Entries() {
		fullwantlist.AddEntry(e.Key, e.Priority)
	}
	mq.out = fullwantlist
	mq.work <- struct{}{}
129 130

	pm.peers[p] = mq
Jeromy's avatar
Jeromy committed
131
	go mq.runQueue(pm.ctx)
Jeromy's avatar
Jeromy committed
132
	return mq
133 134
}

135
func (pm *WantManager) stopPeerHandler(p peer.ID) {
136 137 138 139 140 141
	pq, ok := pm.peers[p]
	if !ok {
		// TODO: log error?
		return
	}

Jeromy's avatar
Jeromy committed
142 143 144 145 146
	pq.refcnt--
	if pq.refcnt > 0 {
		return
	}

147 148 149 150
	close(pq.done)
	delete(pm.peers, p)
}

Jeromy's avatar
Jeromy committed
151
func (mq *msgQueue) runQueue(ctx context.Context) {
152 153 154
	for {
		select {
		case <-mq.work: // there is work to be done
155
			mq.doWork(ctx)
156 157
		case <-mq.done:
			return
Jeromy's avatar
Jeromy committed
158 159
		case <-ctx.Done():
			return
160 161 162 163
		}
	}
}

164
func (mq *msgQueue) doWork(ctx context.Context) {
Jeromy's avatar
Jeromy committed
165
	// allow ten minutes for connections
166 167
	// this includes looking them up in the dht
	// dialing them, and handshaking
Jeromy's avatar
Jeromy committed
168
	conctx, cancel := context.WithTimeout(ctx, time.Minute*10)
169 170 171 172
	defer cancel()

	err := mq.network.ConnectTo(conctx, mq.p)
	if err != nil {
rht's avatar
rht committed
173
		log.Infof("cant connect to peer %s: %s", mq.p, err)
174 175 176 177 178 179 180 181
		// TODO: cant connect, what now?
		return
	}

	// grab outgoing message
	mq.outlk.Lock()
	wlm := mq.out
	if wlm == nil || wlm.Empty() {
Jeromy's avatar
Jeromy committed
182
		mq.outlk.Unlock()
183 184
		return
	}
Jeromy's avatar
Jeromy committed
185 186
	mq.out = nil
	mq.outlk.Unlock()
187

Jeromy's avatar
Jeromy committed
188
	sendctx, cancel := context.WithTimeout(ctx, time.Minute*5)
189 190 191 192 193
	defer cancel()

	// send wantlist updates
	err = mq.network.SendMessage(sendctx, mq.p, wlm)
	if err != nil {
rht's avatar
rht committed
194
		log.Infof("bitswap send error: %s", err)
195 196 197 198 199
		// TODO: what do we do if this fails?
		return
	}
}

200
func (pm *WantManager) Connected(p peer.ID) {
201 202 203 204
	select {
	case pm.connect <- p:
	case <-pm.ctx.Done():
	}
205 206
}

207
func (pm *WantManager) Disconnected(p peer.ID) {
208 209 210 211
	select {
	case pm.disconnect <- p:
	case <-pm.ctx.Done():
	}
212 213 214
}

// TODO: use goprocess here once i trust it
215
func (pm *WantManager) Run() {
216
	tock := time.NewTicker(rebroadcastDelay.Get())
Jeromy's avatar
Jeromy committed
217
	defer tock.Stop()
218 219
	for {
		select {
220 221 222 223 224 225 226 227
		case entries := <-pm.incoming:

			// add changes to our wantlist
			for _, e := range entries {
				if e.Cancel {
					pm.wl.Remove(e.Key)
				} else {
					pm.wl.Add(e.Key, e.Priority)
228 229 230
				}
			}

231 232
			// broadcast those wantlist changes
			for _, p := range pm.peers {
Jeromy's avatar
Jeromy committed
233
				p.addMessage(entries)
234 235
			}

236 237 238 239 240 241 242 243 244 245 246 247 248
		case <-tock.C:
			// resend entire wantlist every so often (REALLY SHOULDNT BE NECESSARY)
			var es []*bsmsg.Entry
			for _, e := range pm.wl.Entries() {
				es = append(es, &bsmsg.Entry{Entry: e})
			}
			for _, p := range pm.peers {
				p.outlk.Lock()
				p.out = bsmsg.New(true)
				p.outlk.Unlock()

				p.addMessage(es)
			}
249
		case p := <-pm.connect:
250
			pm.startPeerHandler(p)
251 252
		case p := <-pm.disconnect:
			pm.stopPeerHandler(p)
253 254 255 256 257 258
		case req := <-pm.peerReqs:
			var peers []peer.ID
			for p := range pm.peers {
				peers = append(peers, p)
			}
			req <- peers
259
		case <-pm.ctx.Done():
260 261 262 263 264
			return
		}
	}
}

Jeromy's avatar
Jeromy committed
265
func (wm *WantManager) newMsgQueue(p peer.ID) *msgQueue {
266 267 268
	mq := new(msgQueue)
	mq.done = make(chan struct{})
	mq.work = make(chan struct{}, 1)
Jeromy's avatar
Jeromy committed
269
	mq.network = wm.network
270
	mq.p = p
Jeromy's avatar
Jeromy committed
271
	mq.refcnt = 1
272 273 274 275

	return mq
}

Jeromy's avatar
Jeromy committed
276
func (mq *msgQueue) addMessage(entries []*bsmsg.Entry) {
Jeromy's avatar
Jeromy committed
277
	mq.outlk.Lock()
278
	defer func() {
Jeromy's avatar
Jeromy committed
279
		mq.outlk.Unlock()
280 281 282 283 284 285
		select {
		case mq.work <- struct{}{}:
		default:
		}
	}()

Jeromy's avatar
Jeromy committed
286 287
	// if we have no message held, or the one we are given is full
	// overwrite the one we are holding
Jeromy's avatar
Jeromy committed
288
	if mq.out == nil {
289
		mq.out = bsmsg.New(false)
290 291 292
	}

	// TODO: add a msg.Combine(...) method
Jeromy's avatar
Jeromy committed
293 294
	// otherwise, combine the one we are holding with the
	// one passed in
Jeromy's avatar
Jeromy committed
295
	for _, e := range entries {
296
		if e.Cancel {
Jeromy's avatar
Jeromy committed
297
			mq.out.Cancel(e.Key)
298
		} else {
Jeromy's avatar
Jeromy committed
299
			mq.out.AddEntry(e.Key, e.Priority)
300 301 302
		}
	}
}