peermanager.go 6.34 KB
Newer Older
1 2 3 4
package peermanager

import (
	"context"
dirkmc's avatar
dirkmc committed
5
	"sync"
6

7
	logging "github.com/ipfs/go-log"
dirkmc's avatar
dirkmc committed
8
	"github.com/ipfs/go-metrics-interface"
9

dirkmc's avatar
dirkmc committed
10
	cid "github.com/ipfs/go-cid"
Raúl Kripalani's avatar
Raúl Kripalani committed
11
	peer "github.com/libp2p/go-libp2p-core/peer"
12 13
)

14 15
var log = logging.Logger("bs:peermgr")

ZenGround0's avatar
ZenGround0 committed
16
// PeerQueue provides a queue of messages to be sent for a single peer.
17
type PeerQueue interface {
dirkmc's avatar
dirkmc committed
18 19 20
	AddBroadcastWantHaves([]cid.Cid)
	AddWants([]cid.Cid, []cid.Cid)
	AddCancels([]cid.Cid)
Dirk McCormick's avatar
Dirk McCormick committed
21
	ResponseReceived(ks []cid.Cid)
22
	Startup()
23 24 25
	Shutdown()
}

dirkmc's avatar
dirkmc committed
26 27 28 29 30
type Session interface {
	ID() uint64
	SignalAvailability(peer.ID, bool)
}

31
// PeerQueueFactory provides a function that will create a PeerQueue.
32
type PeerQueueFactory func(ctx context.Context, p peer.ID) PeerQueue
33

34
// PeerManager manages a pool of peers and sends messages to peers in the pool.
35
type PeerManager struct {
dirkmc's avatar
dirkmc committed
36 37
	// sync access to peerQueues and peerWantManager
	pqLk sync.RWMutex
38
	// peerQueues -- interact through internal utility functions get/set/remove/iterate
39
	peerQueues map[peer.ID]PeerQueue
dirkmc's avatar
dirkmc committed
40
	pwm        *peerWantManager
41

42 43
	createPeerQueue PeerQueueFactory
	ctx             context.Context
dirkmc's avatar
dirkmc committed
44 45 46 47 48 49

	psLk         sync.RWMutex
	sessions     map[uint64]Session
	peerSessions map[peer.ID]map[uint64]struct{}

	self peer.ID
50 51
}

52
// New creates a new PeerManager, given a context and a peerQueueFactory.
dirkmc's avatar
dirkmc committed
53 54
func New(ctx context.Context, createPeerQueue PeerQueueFactory, self peer.ID) *PeerManager {
	wantGauge := metrics.NewCtx(ctx, "wantlist_total", "Number of items in wantlist.").Gauge()
dirkmc's avatar
dirkmc committed
55
	wantBlockGauge := metrics.NewCtx(ctx, "want_blocks_total", "Number of want-blocks in wantlist.").Gauge()
56
	return &PeerManager{
57
		peerQueues:      make(map[peer.ID]PeerQueue),
dirkmc's avatar
dirkmc committed
58
		pwm:             newPeerWantManager(wantGauge, wantBlockGauge),
59 60
		createPeerQueue: createPeerQueue,
		ctx:             ctx,
dirkmc's avatar
dirkmc committed
61 62 63 64
		self:            self,

		sessions:     make(map[uint64]Session),
		peerSessions: make(map[peer.ID]map[uint64]struct{}),
65 66 67
	}
}

dirkmc's avatar
dirkmc committed
68 69 70 71 72
func (pm *PeerManager) AvailablePeers() []peer.ID {
	// TODO: Rate-limit peers
	return pm.ConnectedPeers()
}

73
// ConnectedPeers returns a list of peers this PeerManager is managing.
74
func (pm *PeerManager) ConnectedPeers() []peer.ID {
dirkmc's avatar
dirkmc committed
75 76 77
	pm.pqLk.RLock()
	defer pm.pqLk.RUnlock()

78
	peers := make([]peer.ID, 0, len(pm.peerQueues))
hannahhoward's avatar
hannahhoward committed
79
	for p := range pm.peerQueues {
80
		peers = append(peers, p)
hannahhoward's avatar
hannahhoward committed
81
	}
82
	return peers
83 84
}

85 86
// Connected is called to add a new peer to the pool, and send it an initial set
// of wants.
87
func (pm *PeerManager) Connected(p peer.ID) {
dirkmc's avatar
dirkmc committed
88 89 90
	pm.pqLk.Lock()
	defer pm.pqLk.Unlock()

hannahhoward's avatar
hannahhoward committed
91
	pq := pm.getOrCreate(p)
92 93

	// Inform the peer want manager that there's a new peer
94 95
	pm.pwm.addPeer(pq, p)

96 97
	// Inform the sessions that the peer has connected
	pm.signalAvailability(p, true)
98 99
}

100 101
// Disconnected is called to remove a peer from the pool.
func (pm *PeerManager) Disconnected(p peer.ID) {
dirkmc's avatar
dirkmc committed
102 103 104
	pm.pqLk.Lock()
	defer pm.pqLk.Unlock()

105
	pq, ok := pm.peerQueues[p]
106

hannahhoward's avatar
hannahhoward committed
107 108 109 110
	if !ok {
		return
	}

dirkmc's avatar
dirkmc committed
111 112 113 114
	// Inform the sessions that the peer has disconnected
	pm.signalAvailability(p, false)

	// Clean up the peer
115
	delete(pm.peerQueues, p)
116
	pq.Shutdown()
117
	pm.pwm.removePeer(p)
118 119
}

120 121 122
// ResponseReceived is called when a message is received from the network.
// ks is the set of blocks, HAVEs and DONT_HAVEs in the message
// Note that this is just used to calculate latency.
Dirk McCormick's avatar
Dirk McCormick committed
123
func (pm *PeerManager) ResponseReceived(p peer.ID, ks []cid.Cid) {
124 125 126 127 128
	pm.pqLk.Lock()
	pq, ok := pm.peerQueues[p]
	pm.pqLk.Unlock()

	if ok {
Dirk McCormick's avatar
Dirk McCormick committed
129
		pq.ResponseReceived(ks)
130 131 132
	}
}

133 134 135 136
// BroadcastWantHaves broadcasts want-haves to all peers (used by the session
// to discover seeds).
// For each peer it filters out want-haves that have previously been sent to
// the peer.
dirkmc's avatar
dirkmc committed
137 138 139 140
func (pm *PeerManager) BroadcastWantHaves(ctx context.Context, wantHaves []cid.Cid) {
	pm.pqLk.Lock()
	defer pm.pqLk.Unlock()

141
	pm.pwm.broadcastWantHaves(wantHaves)
dirkmc's avatar
dirkmc committed
142 143
}

144 145
// SendWants sends the given want-blocks and want-haves to the given peer.
// It filters out wants that have previously been sent to the peer.
dirkmc's avatar
dirkmc committed
146 147 148 149
func (pm *PeerManager) SendWants(ctx context.Context, p peer.ID, wantBlocks []cid.Cid, wantHaves []cid.Cid) {
	pm.pqLk.Lock()
	defer pm.pqLk.Unlock()

150 151
	if _, ok := pm.peerQueues[p]; ok {
		pm.pwm.sendWants(p, wantBlocks, wantHaves)
dirkmc's avatar
dirkmc committed
152 153 154
	}
}

155 156
// SendCancels sends cancels for the given keys to all peers who had previously
// received a want for those keys.
dirkmc's avatar
dirkmc committed
157 158 159 160 161
func (pm *PeerManager) SendCancels(ctx context.Context, cancelKs []cid.Cid) {
	pm.pqLk.Lock()
	defer pm.pqLk.Unlock()

	// Send a CANCEL to each peer that has been sent a want-block or want-have
162
	pm.pwm.sendCancels(cancelKs)
163
}
164

165
// CurrentWants returns the list of pending wants (both want-haves and want-blocks).
dirkmc's avatar
dirkmc committed
166 167 168 169
func (pm *PeerManager) CurrentWants() []cid.Cid {
	pm.pqLk.RLock()
	defer pm.pqLk.RUnlock()

170
	return pm.pwm.getWants()
171 172 173 174 175 176 177
}

// CurrentWantBlocks returns the list of pending want-blocks
func (pm *PeerManager) CurrentWantBlocks() []cid.Cid {
	pm.pqLk.RLock()
	defer pm.pqLk.RUnlock()

178
	return pm.pwm.getWantBlocks()
dirkmc's avatar
dirkmc committed
179 180
}

181
// CurrentWantHaves returns the list of pending want-haves
dirkmc's avatar
dirkmc committed
182 183 184 185
func (pm *PeerManager) CurrentWantHaves() []cid.Cid {
	pm.pqLk.RLock()
	defer pm.pqLk.RUnlock()

186
	return pm.pwm.getWantHaves()
dirkmc's avatar
dirkmc committed
187 188
}

189 190
func (pm *PeerManager) getOrCreate(p peer.ID) PeerQueue {
	pq, ok := pm.peerQueues[p]
191
	if !ok {
192
		pq = pm.createPeerQueue(pm.ctx, p)
193
		pq.Startup()
194
		pm.peerQueues[p] = pq
195
	}
196
	return pq
197
}
dirkmc's avatar
dirkmc committed
198

199 200
// RegisterSession tells the PeerManager that the given session is interested
// in events about the given peer.
dirkmc's avatar
dirkmc committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
func (pm *PeerManager) RegisterSession(p peer.ID, s Session) bool {
	pm.psLk.Lock()
	defer pm.psLk.Unlock()

	if _, ok := pm.sessions[s.ID()]; !ok {
		pm.sessions[s.ID()] = s
	}

	if _, ok := pm.peerSessions[p]; !ok {
		pm.peerSessions[p] = make(map[uint64]struct{})
	}
	pm.peerSessions[p][s.ID()] = struct{}{}

	_, ok := pm.peerQueues[p]
	return ok
}

218 219
// UnregisterSession tells the PeerManager that the given session is no longer
// interested in PeerManager events.
dirkmc's avatar
dirkmc committed
220 221 222 223 224 225 226 227 228 229 230 231 232 233
func (pm *PeerManager) UnregisterSession(ses uint64) {
	pm.psLk.Lock()
	defer pm.psLk.Unlock()

	for p := range pm.peerSessions {
		delete(pm.peerSessions[p], ses)
		if len(pm.peerSessions[p]) == 0 {
			delete(pm.peerSessions, p)
		}
	}

	delete(pm.sessions, ses)
}

234 235
// signalAvailability is called when a peer's connectivity changes.
// It informs interested sessions.
dirkmc's avatar
dirkmc committed
236
func (pm *PeerManager) signalAvailability(p peer.ID, isConnected bool) {
237 238 239 240 241 242 243
	sesIds, ok := pm.peerSessions[p]
	if !ok {
		return
	}
	for sesId := range sesIds {
		if s, ok := pm.sessions[sesId]; ok {
			s.SignalAvailability(p, isConnected)
dirkmc's avatar
dirkmc committed
244 245 246
		}
	}
}