wantmanager.go 5.96 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"
Jeromy's avatar
Jeromy committed
12
	peer "gx/ipfs/QmUBogf4nUefBjmYjn6jfsfPJRkmDGSeMhNj4usRKq69f4/go-libp2p/p2p/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 19 20
	// sync channels for Run loop
	incoming   chan []*bsmsg.Entry
	connect    chan peer.ID // notification channel for new peers connecting
	disconnect chan peer.ID // notification channel for peers disconnecting
21

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

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

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

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

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

type msgQueue struct {
	p peer.ID

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

Jeromy's avatar
Jeromy committed
59 60
	refcnt int

61 62 63 64
	work chan struct{}
	done chan struct{}
}

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

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

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

func (pm *WantManager) SendBlock(ctx context.Context, env *engine.Envelope) {
92 93 94 95
	// Blocks need to be sent synchronously to maintain proper backpressure
	// throughout the network stack
	defer env.Sent()

96
	msg := bsmsg.New(false)
97
	msg.AddBlock(env.Block)
Jeromy's avatar
Jeromy committed
98
	log.Infof("Sending block %s to %s", env.Peer, env.Block)
Jeromy's avatar
Jeromy committed
99
	err := pm.network.SendMessage(ctx, env.Peer, msg)
100
	if err != nil {
rht's avatar
rht committed
101
		log.Infof("sendblock error: %s", err)
102 103 104
	}
}

105
func (pm *WantManager) startPeerHandler(p peer.ID) *msgQueue {
Jeromy's avatar
Jeromy committed
106
	mq, ok := pm.peers[p]
107
	if ok {
Jeromy's avatar
Jeromy committed
108
		mq.refcnt++
Jeromy's avatar
Jeromy committed
109
		return nil
110 111
	}

Jeromy's avatar
Jeromy committed
112
	mq = pm.newMsgQueue(p)
113 114

	// new peer, we will want to give them our full wantlist
115
	fullwantlist := bsmsg.New(true)
116 117 118 119 120
	for _, e := range pm.wl.Entries() {
		fullwantlist.AddEntry(e.Key, e.Priority)
	}
	mq.out = fullwantlist
	mq.work <- struct{}{}
121 122

	pm.peers[p] = mq
Jeromy's avatar
Jeromy committed
123
	go mq.runQueue(pm.ctx)
Jeromy's avatar
Jeromy committed
124
	return mq
125 126
}

127
func (pm *WantManager) stopPeerHandler(p peer.ID) {
128 129 130 131 132 133
	pq, ok := pm.peers[p]
	if !ok {
		// TODO: log error?
		return
	}

Jeromy's avatar
Jeromy committed
134 135 136 137 138
	pq.refcnt--
	if pq.refcnt > 0 {
		return
	}

139 140 141 142
	close(pq.done)
	delete(pm.peers, p)
}

Jeromy's avatar
Jeromy committed
143
func (mq *msgQueue) runQueue(ctx context.Context) {
144 145 146
	for {
		select {
		case <-mq.work: // there is work to be done
147
			mq.doWork(ctx)
148 149
		case <-mq.done:
			return
Jeromy's avatar
Jeromy committed
150 151
		case <-ctx.Done():
			return
152 153 154 155
		}
	}
}

156
func (mq *msgQueue) doWork(ctx context.Context) {
Jeromy's avatar
Jeromy committed
157
	// allow ten minutes for connections
158 159
	// this includes looking them up in the dht
	// dialing them, and handshaking
Jeromy's avatar
Jeromy committed
160
	conctx, cancel := context.WithTimeout(ctx, time.Minute*10)
161 162 163 164
	defer cancel()

	err := mq.network.ConnectTo(conctx, mq.p)
	if err != nil {
rht's avatar
rht committed
165
		log.Infof("cant connect to peer %s: %s", mq.p, err)
166 167 168 169 170 171 172 173
		// 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
174
		mq.outlk.Unlock()
175 176
		return
	}
Jeromy's avatar
Jeromy committed
177 178
	mq.out = nil
	mq.outlk.Unlock()
179

Jeromy's avatar
Jeromy committed
180
	sendctx, cancel := context.WithTimeout(ctx, time.Minute*5)
181 182 183 184 185
	defer cancel()

	// send wantlist updates
	err = mq.network.SendMessage(sendctx, mq.p, wlm)
	if err != nil {
rht's avatar
rht committed
186
		log.Infof("bitswap send error: %s", err)
187 188 189 190 191
		// TODO: what do we do if this fails?
		return
	}
}

192
func (pm *WantManager) Connected(p peer.ID) {
193 194 195 196
	select {
	case pm.connect <- p:
	case <-pm.ctx.Done():
	}
197 198
}

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

// TODO: use goprocess here once i trust it
207
func (pm *WantManager) Run() {
208
	tock := time.NewTicker(rebroadcastDelay.Get())
Jeromy's avatar
Jeromy committed
209
	defer tock.Stop()
210 211
	for {
		select {
212 213 214 215 216 217 218 219
		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)
220 221 222
				}
			}

223 224
			// broadcast those wantlist changes
			for _, p := range pm.peers {
Jeromy's avatar
Jeromy committed
225
				p.addMessage(entries)
226 227
			}

228 229 230 231 232 233 234 235 236 237 238 239 240
		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)
			}
241
		case p := <-pm.connect:
242
			pm.startPeerHandler(p)
243 244
		case p := <-pm.disconnect:
			pm.stopPeerHandler(p)
245
		case <-pm.ctx.Done():
246 247 248 249 250
			return
		}
	}
}

Jeromy's avatar
Jeromy committed
251
func (wm *WantManager) newMsgQueue(p peer.ID) *msgQueue {
252 253 254
	mq := new(msgQueue)
	mq.done = make(chan struct{})
	mq.work = make(chan struct{}, 1)
Jeromy's avatar
Jeromy committed
255
	mq.network = wm.network
256
	mq.p = p
Jeromy's avatar
Jeromy committed
257
	mq.refcnt = 1
258 259 260 261

	return mq
}

Jeromy's avatar
Jeromy committed
262
func (mq *msgQueue) addMessage(entries []*bsmsg.Entry) {
Jeromy's avatar
Jeromy committed
263
	mq.outlk.Lock()
264
	defer func() {
Jeromy's avatar
Jeromy committed
265
		mq.outlk.Unlock()
266 267 268 269 270 271
		select {
		case mq.work <- struct{}{}:
		default:
		}
	}()

Jeromy's avatar
Jeromy committed
272 273
	// 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
274
	if mq.out == nil {
275
		mq.out = bsmsg.New(false)
276 277 278
	}

	// TODO: add a msg.Combine(...) method
Jeromy's avatar
Jeromy committed
279 280
	// otherwise, combine the one we are holding with the
	// one passed in
Jeromy's avatar
Jeromy committed
281
	for _, e := range entries {
282
		if e.Cancel {
Jeromy's avatar
Jeromy committed
283
			mq.out.Cancel(e.Key)
284
		} else {
Jeromy's avatar
Jeromy committed
285
			mq.out.AddEntry(e.Key, e.Priority)
286 287 288
		}
	}
}