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

import (
	"sync"
5
	"time"
6 7 8 9 10

	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
	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 13 14 15
	peer "github.com/ipfs/go-ipfs/p2p/peer"
	u "github.com/ipfs/go-ipfs/util"
)

16
type WantManager struct {
17 18
	receiver bsnet.Receiver

19 20 21 22 23 24
	incoming chan []*bsmsg.Entry

	// notification channel for new peers connecting
	connect chan peer.ID

	// notification channel for peers disconnecting
25 26 27 28
	disconnect chan peer.ID

	peers map[peer.ID]*msgQueue

29 30
	wl *wantlist.Wantlist

31
	network bsnet.BitSwapNetwork
32 33

	ctx context.Context
34 35
}

36
func NewWantManager(ctx context.Context, network bsnet.BitSwapNetwork) *WantManager {
37 38
	return &WantManager{
		incoming:   make(chan []*bsmsg.Entry, 10),
39 40 41
		connect:    make(chan peer.ID, 10),
		disconnect: make(chan peer.ID, 10),
		peers:      make(map[peer.ID]*msgQueue),
42
		wl:         wantlist.New(),
43
		network:    network,
44
		ctx:        ctx,
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
	}
}

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

type cancellation struct {
	who peer.ID
	blk u.Key
}

type msgQueue struct {
	p peer.ID

Jeromy's avatar
Jeromy committed
61 62
	outlk sync.Mutex
	out   bsmsg.BitSwapMessage
63 64 65 66 67

	work chan struct{}
	done chan struct{}
}

68
func (pm *WantManager) WantBlocks(ks []u.Key) {
Jeromy's avatar
Jeromy committed
69
	log.Infof("want blocks: %s", ks)
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
	pm.addEntries(ks, false)
}

func (pm *WantManager) CancelWants(ks []u.Key) {
	pm.addEntries(ks, true)
}

func (pm *WantManager) addEntries(ks []u.Key, cancel bool) {
	var entries []*bsmsg.Entry
	for i, k := range ks {
		entries = append(entries, &bsmsg.Entry{
			Cancel: cancel,
			Entry: wantlist.Entry{
				Key:      k,
				Priority: kMaxPriority - i,
			},
		})
	}
88 89 90 91
	select {
	case pm.incoming <- entries:
	case <-pm.ctx.Done():
	}
92 93 94
}

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

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

108
func (pm *WantManager) startPeerHandler(p peer.ID) *msgQueue {
109 110 111
	_, ok := pm.peers[p]
	if ok {
		// TODO: log an error?
Jeromy's avatar
Jeromy committed
112
		return nil
113 114
	}

115 116 117
	mq := newMsgQueue(p)

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

	pm.peers[p] = mq
126
	go pm.runQueue(mq)
Jeromy's avatar
Jeromy committed
127
	return mq
128 129
}

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

	close(pq.done)
	delete(pm.peers, p)
}

141
func (pm *WantManager) runQueue(mq *msgQueue) {
142 143 144 145
	for {
		select {
		case <-mq.work: // there is work to be done

146
			err := pm.network.ConnectTo(pm.ctx, mq.p)
147
			if err != nil {
Jeromy's avatar
Jeromy committed
148
				log.Errorf("cant connect to peer %s: %s", mq.p, err)
149
				// TODO: cant connect, what now?
Jeromy's avatar
Jeromy committed
150
				continue
151 152
			}

153
			// grab outgoing message
Jeromy's avatar
Jeromy committed
154 155
			mq.outlk.Lock()
			wlm := mq.out
Jeromy's avatar
Jeromy committed
156 157
			if wlm == nil || wlm.Empty() {
				mq.outlk.Unlock()
158 159
				continue
			}
Jeromy's avatar
Jeromy committed
160 161
			mq.out = nil
			mq.outlk.Unlock()
162 163

			// send wantlist updates
164
			err = pm.network.SendMessage(pm.ctx, mq.p, wlm)
165 166 167
			if err != nil {
				log.Error("bitswap send error: ", err)
				// TODO: what do we do if this fails?
168 169 170 171 172 173 174
			}
		case <-mq.done:
			return
		}
	}
}

175
func (pm *WantManager) Connected(p peer.ID) {
176 177 178
	pm.connect <- p
}

179
func (pm *WantManager) Disconnected(p peer.ID) {
180 181 182 183
	pm.disconnect <- p
}

// TODO: use goprocess here once i trust it
184
func (pm *WantManager) Run() {
185
	tock := time.NewTicker(rebroadcastDelay.Get())
186 187
	for {
		select {
188 189 190 191 192 193 194 195
		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)
196 197 198
				}
			}

199 200
			// broadcast those wantlist changes
			for _, p := range pm.peers {
Jeromy's avatar
Jeromy committed
201
				p.addMessage(entries)
202 203
			}

204 205 206 207 208 209 210 211 212 213 214 215 216
		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)
			}
217
		case p := <-pm.connect:
218
			pm.startPeerHandler(p)
219 220
		case p := <-pm.disconnect:
			pm.stopPeerHandler(p)
221
		case <-pm.ctx.Done():
222 223 224 225 226
			return
		}
	}
}

227 228 229 230 231 232 233 234 235
func newMsgQueue(p peer.ID) *msgQueue {
	mq := new(msgQueue)
	mq.done = make(chan struct{})
	mq.work = make(chan struct{}, 1)
	mq.p = p

	return mq
}

Jeromy's avatar
Jeromy committed
236
func (mq *msgQueue) addMessage(entries []*bsmsg.Entry) {
Jeromy's avatar
Jeromy committed
237
	mq.outlk.Lock()
238
	defer func() {
Jeromy's avatar
Jeromy committed
239
		mq.outlk.Unlock()
240 241 242 243 244 245
		select {
		case mq.work <- struct{}{}:
		default:
		}
	}()

Jeromy's avatar
Jeromy committed
246 247
	// 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
248
	if mq.out == nil {
249
		mq.out = bsmsg.New(false)
250 251 252
	}

	// TODO: add a msg.Combine(...) method
Jeromy's avatar
Jeromy committed
253 254
	// otherwise, combine the one we are holding with the
	// one passed in
Jeromy's avatar
Jeromy committed
255
	for _, e := range entries {
256
		if e.Cancel {
Jeromy's avatar
Jeromy committed
257
			mq.out.Cancel(e.Key)
258
		} else {
Jeromy's avatar
Jeromy committed
259
			mq.out.AddEntry(e.Key, e.Priority)
260 261 262
		}
	}
}