-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathpeermanager.go
1536 lines (1353 loc) · 46.4 KB
/
peermanager.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package p2p
import (
"context"
"errors"
"fmt"
"math"
"math/rand"
"sort"
"strings"
"sync"
"time"
"github.com/tendermint/tendermint/libs/log"
"github.com/gogo/protobuf/proto"
"github.com/google/orderedcode"
dbm "github.com/tendermint/tm-db"
tmsync "github.com/tendermint/tendermint/internal/libs/sync"
p2pproto "github.com/tendermint/tendermint/proto/tendermint/p2p"
"github.com/tendermint/tendermint/types"
)
const (
// retryNever is returned by retryDelay() when retries are disabled.
retryNever time.Duration = math.MaxInt64
// DefaultMutableScore is the default score for a peer during initialization
DefaultMutableScore int64 = 10
)
// PeerStatus is a peer status.
//
// The peer manager has many more internal states for a peer (e.g. dialing,
// connected, evicting, and so on), which are tracked separately. PeerStatus is
// for external use outside of the peer manager.
type PeerStatus string
const (
PeerStatusUp PeerStatus = "up" // connected and ready
PeerStatusDown PeerStatus = "down" // disconnected
PeerStatusGood PeerStatus = "good" // peer observed as good
PeerStatusBad PeerStatus = "bad" // peer observed as bad
)
// PeerScore is a numeric score assigned to a peer (higher is better).
type PeerScore uint8
const (
PeerScoreUnconditional PeerScore = math.MaxUint8 // unconditional peers
PeerScorePersistent PeerScore = PeerScoreUnconditional - 1 // persistent peers
MaxPeerScoreNotPersistent PeerScore = PeerScorePersistent - 1
)
// PeerUpdate is a peer update event sent via PeerUpdates.
type PeerUpdate struct {
NodeID types.NodeID
Status PeerStatus
Channels ChannelIDSet
}
// PeerUpdates is a peer update subscription with notifications about peer
// events (currently just status changes).
type PeerUpdates struct {
routerUpdatesCh chan PeerUpdate
reactorUpdatesCh chan PeerUpdate
}
// NewPeerUpdates creates a new PeerUpdates subscription. It is primarily for
// internal use, callers should typically use PeerManager.Subscribe(). The
// subscriber must call Close() when done.
func NewPeerUpdates(updatesCh chan PeerUpdate, buf int) *PeerUpdates {
return &PeerUpdates{
reactorUpdatesCh: updatesCh,
routerUpdatesCh: make(chan PeerUpdate, buf),
}
}
// Updates returns a channel for consuming peer updates.
func (pu *PeerUpdates) Updates() <-chan PeerUpdate {
return pu.reactorUpdatesCh
}
// SendUpdate pushes information about a peer into the routing layer,
// presumably from a peer.
func (pu *PeerUpdates) SendUpdate(ctx context.Context, update PeerUpdate) {
select {
case <-ctx.Done():
case pu.routerUpdatesCh <- update:
}
}
// PeerManagerOptions specifies options for a PeerManager.
type PeerManagerOptions struct {
// PersistentPeers are peers that we want to maintain persistent connections
// to. These will be scored higher than other peers, and if
// MaxConnectedUpgrade is non-zero any lower-scored peers will be evicted if
// necessary to make room for these.
PersistentPeers []types.NodeID
// Peers to which a connection will be (re)established ignoring any existing limits
UnconditionalPeers []types.NodeID
// Only include those peers for block sync
BlockSyncPeers []types.NodeID
// MaxPeers is the maximum number of peers to track information about, i.e.
// store in the peer store. When exceeded, the lowest-scored unconnected peers
// will be deleted. 0 means no limit.
MaxPeers uint16
// MaxConnected is the maximum number of connected peers (inbound and
// outbound). 0 means no limit.
MaxConnected uint16
// MaxConnectedUpgrade is the maximum number of additional connections to
// use for probing any better-scored peers to upgrade to when all connection
// slots are full. 0 disables peer upgrading.
//
// For example, if we are already connected to MaxConnected peers, but we
// know or learn about better-scored peers (e.g. configured persistent
// peers) that we are not connected too, then we can probe these peers by
// using up to MaxConnectedUpgrade connections, and once connected evict the
// lowest-scored connected peers. This also works for inbound connections,
// i.e. if a higher-scored peer attempts to connect to us, we can accept
// the connection and evict a lower-scored peer.
MaxConnectedUpgrade uint16
// MinRetryTime is the minimum time to wait between retries. Retry times
// double for each retry, up to MaxRetryTime. 0 disables retries.
MinRetryTime time.Duration
// MaxRetryTime is the maximum time to wait between retries. 0 means
// no maximum, in which case the retry time will keep doubling.
MaxRetryTime time.Duration
// MaxRetryTimePersistent is the maximum time to wait between retries for
// peers listed in PersistentPeers. 0 uses MaxRetryTime instead.
MaxRetryTimePersistent time.Duration
// RetryTimeJitter is the upper bound of a random interval added to
// retry times, to avoid thundering herds. 0 disables jitter.
RetryTimeJitter time.Duration
// PeerScores sets fixed scores for specific peers. It is mainly used
// for testing. A score of 0 is ignored.
PeerScores map[types.NodeID]PeerScore
// PrivatePeerIDs defines a set of NodeID objects which the PEX reactor will
// consider private and never gossip.
PrivatePeers map[types.NodeID]struct{}
// SelfAddress is the address that will be advertised to peers for them to dial back to us.
// If Hostname and Port are unset, Advertise() will include no self-announcement
SelfAddress NodeAddress
// persistentPeers provides fast PersistentPeers lookups. It is built
// by optimize().
persistentPeers map[types.NodeID]bool
// List of node IDs, to which a connection will be (re)established ignoring any existing limits
unconditionalPeers map[types.NodeID]struct{}
// blocksyncPeers provides fast blocksyncPeers lookups.
blocksyncPeers map[types.NodeID]bool
}
// Validate validates the options.
func (o *PeerManagerOptions) Validate() error {
for _, id := range o.PersistentPeers {
if err := id.Validate(); err != nil {
return fmt.Errorf("invalid PersistentPeer ID %q: %w", id, err)
}
}
for id := range o.PrivatePeers {
if err := id.Validate(); err != nil {
return fmt.Errorf("invalid private peer ID %q: %w", id, err)
}
}
if o.MaxConnected > 0 && len(o.PersistentPeers) > int(o.MaxConnected) {
return fmt.Errorf("number of persistent peers %v can't exceed MaxConnected %v",
len(o.PersistentPeers), o.MaxConnected)
}
if o.MaxPeers > 0 {
if o.MaxConnected == 0 || o.MaxConnected+o.MaxConnectedUpgrade > o.MaxPeers {
return fmt.Errorf("MaxConnected %v and MaxConnectedUpgrade %v can't exceed MaxPeers %v",
o.MaxConnected, o.MaxConnectedUpgrade, o.MaxPeers)
}
}
if o.MaxRetryTime > 0 {
if o.MinRetryTime == 0 {
return errors.New("can't set MaxRetryTime without MinRetryTime")
}
if o.MinRetryTime > o.MaxRetryTime {
return fmt.Errorf("MinRetryTime %v is greater than MaxRetryTime %v",
o.MinRetryTime, o.MaxRetryTime)
}
}
if o.MaxRetryTimePersistent > 0 {
if o.MinRetryTime == 0 {
return errors.New("can't set MaxRetryTimePersistent without MinRetryTime")
}
if o.MinRetryTime > o.MaxRetryTimePersistent {
return fmt.Errorf("MinRetryTime %v is greater than MaxRetryTimePersistent %v",
o.MinRetryTime, o.MaxRetryTimePersistent)
}
}
return nil
}
// isPersistentPeer checks if a peer is in PersistentPeers. It will panic
// if called before optimize().
func (o *PeerManagerOptions) isPersistent(id types.NodeID) bool {
if o.persistentPeers == nil {
panic("isPersistentPeer() called before optimize()")
}
return o.persistentPeers[id]
}
func (o *PeerManagerOptions) isBlockSync(id types.NodeID) bool {
if o.blocksyncPeers == nil {
panic("isBlockSync() called before optimize()")
}
return o.blocksyncPeers[id]
}
func (o *PeerManagerOptions) isUnconditional(id types.NodeID) bool {
if o.unconditionalPeers == nil {
panic("isUnconditional() called before optimize()")
}
_, ok := o.unconditionalPeers[id]
return ok
}
// optimize optimizes operations by pregenerating lookup structures. It's a
// separate method instead of memoizing during calls to avoid dealing with
// concurrency and mutex overhead.
func (o *PeerManagerOptions) optimize() {
o.persistentPeers = make(map[types.NodeID]bool, len(o.PersistentPeers))
for _, p := range o.PersistentPeers {
o.persistentPeers[p] = true
}
o.blocksyncPeers = make(map[types.NodeID]bool, len(o.BlockSyncPeers))
for _, p := range o.BlockSyncPeers {
o.blocksyncPeers[p] = true
}
o.unconditionalPeers = make(map[types.NodeID]struct{}, len(o.UnconditionalPeers))
for _, p := range o.UnconditionalPeers {
o.unconditionalPeers[p] = struct{}{}
}
}
// PeerManager manages peer lifecycle information, using a peerStore for
// underlying storage. Its primary purpose is to determine which peer to connect
// to next (including retry timers), make sure a peer only has a single active
// connection (either inbound or outbound), and evict peers to make room for
// higher-scored peers. It does not manage actual connections (this is handled
// by the Router), only the peer lifecycle state.
//
// For an outbound connection, the flow is as follows:
// - DialNext: return a peer address to dial, mark peer as dialing.
// - DialFailed: report a dial failure, unmark as dialing.
// - Dialed: report a dial success, unmark as dialing and mark as connected
// (errors if already connected, e.g. by Accepted).
// - Ready: report routing is ready, mark as ready and broadcast PeerStatusUp.
// - Disconnected: report peer disconnect, unmark as connected and broadcasts
// PeerStatusDown.
//
// For an inbound connection, the flow is as follows:
// - Accepted: report inbound connection success, mark as connected (errors if
// already connected, e.g. by Dialed).
// - Ready: report routing is ready, mark as ready and broadcast PeerStatusUp.
// - Disconnected: report peer disconnect, unmark as connected and broadcasts
// PeerStatusDown.
//
// When evicting peers, either because peers are explicitly scheduled for
// eviction or we are connected to too many peers, the flow is as follows:
// - EvictNext: if marked evict and connected, unmark evict and mark evicting.
// If beyond MaxConnected, pick lowest-scored peer and mark evicting.
// - Disconnected: unmark connected, evicting, evict, and broadcast a
// PeerStatusDown peer update.
//
// If all connection slots are full (at MaxConnections), we can use up to
// MaxConnectionsUpgrade additional connections to probe any higher-scored
// unconnected peers, and if we reach them (or they reach us) we allow the
// connection and evict a lower-scored peer. We mark the lower-scored peer as
// upgrading[from]=to to make sure no other higher-scored peers can claim the
// same one for an upgrade. The flow is as follows:
// - Accepted: if upgrade is possible, mark connected and add lower-scored to evict.
// - DialNext: if upgrade is possible, mark upgrading[from]=to and dialing.
// - DialFailed: unmark upgrading[from]=to and dialing.
// - Dialed: unmark upgrading[from]=to and dialing, mark as connected, add
// lower-scored to evict.
// - EvictNext: pick peer from evict, mark as evicting.
// - Disconnected: unmark connected, upgrading[from]=to, evict, evicting.
type PeerManager struct {
logger log.Logger
selfID types.NodeID
options PeerManagerOptions
rand *rand.Rand
dialWaker *tmsync.Waker // wakes up DialNext() on relevant peer changes
evictWaker *tmsync.Waker // wakes up EvictNext() on relevant peer changes
mtx sync.Mutex
store *peerStore
subscriptions map[*PeerUpdates]*PeerUpdates // keyed by struct identity (address)
dialing map[types.NodeID]bool // peers being dialed (DialNext → Dialed/DialFail)
upgrading map[types.NodeID]types.NodeID // peers claimed for upgrade (DialNext → Dialed/DialFail)
connected map[types.NodeID]bool // connected peers (Dialed/Accepted → Disconnected)
ready map[types.NodeID]bool // ready peers (Ready → Disconnected)
evict map[types.NodeID]bool // peers scheduled for eviction (Connected → EvictNext)
evicting map[types.NodeID]bool // peers being evicted (EvictNext → Disconnected)
metrics *Metrics
}
// NewPeerManager creates a new peer manager.
func NewPeerManager(
logger log.Logger,
selfID types.NodeID,
peerDB dbm.DB,
options PeerManagerOptions,
metrics *Metrics,
) (*PeerManager, error) {
if selfID == "" {
return nil, errors.New("self ID not given")
}
if err := options.Validate(); err != nil {
return nil, err
}
options.optimize()
store, err := newPeerStore(peerDB, metrics)
if err != nil {
return nil, err
}
peerManager := &PeerManager{
logger: logger,
selfID: selfID,
options: options,
rand: rand.New(rand.NewSource(time.Now().UnixNano())), // nolint:gosec
dialWaker: tmsync.NewWaker(),
evictWaker: tmsync.NewWaker(),
store: store,
dialing: map[types.NodeID]bool{},
upgrading: map[types.NodeID]types.NodeID{},
connected: map[types.NodeID]bool{},
ready: map[types.NodeID]bool{},
evict: map[types.NodeID]bool{},
evicting: map[types.NodeID]bool{},
subscriptions: map[*PeerUpdates]*PeerUpdates{},
metrics: metrics,
}
if err = peerManager.configurePeers(); err != nil {
return nil, err
}
if err = peerManager.prunePeers(); err != nil {
return nil, err
}
return peerManager, nil
}
// configurePeers configures peers in the peer store with ephemeral runtime
// configuration, e.g. PersistentPeers. It also removes ourself, if we're in the
// peer store. The caller must hold the mutex lock.
func (m *PeerManager) configurePeers() error {
if err := m.store.Delete(m.selfID); err != nil {
return err
}
configure := map[types.NodeID]bool{}
for _, id := range m.options.PersistentPeers {
configure[id] = true
}
for _, id := range m.options.UnconditionalPeers {
configure[id] = true
}
for _, id := range m.options.BlockSyncPeers {
configure[id] = true
}
for id := range m.options.PeerScores {
configure[id] = true
}
for id := range configure {
if peer, ok := m.store.Get(id); ok {
if err := m.store.Set(m.configurePeer(peer)); err != nil {
return err
}
}
}
return nil
}
// configurePeer configures a peer with ephemeral runtime configuration.
func (m *PeerManager) configurePeer(peer peerInfo) peerInfo {
peer.Persistent = m.options.isPersistent(peer.ID)
peer.Unconditional = m.options.isUnconditional(peer.ID)
peer.BlockSync = m.options.isBlockSync(peer.ID)
peer.FixedScore = m.options.PeerScores[peer.ID]
return peer
}
// newPeerInfo creates a peerInfo for a new peer. Each peer will start with a positive MutableScore.
// If a peer is misbehaving, we will decrease the MutableScore, and it will be ranked down.
func (m *PeerManager) newPeerInfo(id types.NodeID) peerInfo {
peerInfo := peerInfo{
ID: id,
AddressInfo: map[NodeAddress]*peerAddressInfo{},
MutableScore: DefaultMutableScore, // Should start with a default value above 0
}
return m.configurePeer(peerInfo)
}
// prunePeers removes low-scored peers from the peer store if it contains more
// than MaxPeers peers. The caller must hold the mutex lock.
func (m *PeerManager) prunePeers() error {
if m.options.MaxPeers == 0 || m.store.Size() <= int(m.options.MaxPeers) {
return nil
}
ranked := m.store.Ranked()
for i := len(ranked) - 1; i >= 0; i-- {
peerID := ranked[i].ID
switch {
case m.store.Size() <= int(m.options.MaxPeers):
return nil
case m.dialing[peerID]:
case m.connected[peerID]:
default:
if err := m.store.Delete(peerID); err != nil {
return err
}
}
}
return nil
}
// Add adds a peer to the manager, given as an address. If the peer already
// exists, the address is added to it if it isn't already present. This will push
// low scoring peers out of the address book if it exceeds the maximum size.
func (m *PeerManager) Add(address NodeAddress) (bool, error) {
if err := address.Validate(); err != nil {
return false, err
}
if address.NodeID == m.selfID {
m.logger.Info("can't add self to peer store, skipping address", "address", address.String(), "self", m.selfID)
return false, nil
}
m.mtx.Lock()
defer m.mtx.Unlock()
peer, ok := m.store.Get(address.NodeID)
if !ok {
peer = m.newPeerInfo(address.NodeID)
}
_, ok = peer.AddressInfo[address]
// if we already have the peer address, there's no need to continue
if ok {
return false, nil
}
// else add the new address
if len(peer.AddressInfo) == 0 {
peer.AddressInfo = make(map[NodeAddress]*peerAddressInfo)
}
peer.AddressInfo[address] = &peerAddressInfo{Address: address}
m.logger.Info(fmt.Sprintf("Adding new peer %s with address %s to peer store\n", peer.ID, address.String()))
if err := m.store.Set(peer); err != nil {
return false, err
}
if err := m.prunePeers(); err != nil {
return true, err
}
m.dialWaker.Wake()
return true, nil
}
func (m *PeerManager) GetBlockSyncPeers() map[types.NodeID]bool {
return m.options.blocksyncPeers
}
// PeerRatio returns the ratio of peer addresses stored to the maximum size.
func (m *PeerManager) PeerRatio() float64 {
m.mtx.Lock()
defer m.mtx.Unlock()
if m.options.MaxPeers == 0 {
return 0
}
return float64(m.store.Size()) / float64(m.options.MaxPeers)
}
func (m *PeerManager) HasMaxPeerCapacity() bool {
m.mtx.Lock()
defer m.mtx.Unlock()
return m.NumConnected() >= int(m.options.MaxConnected)
}
// DialNext finds an appropriate peer address to dial, and marks it as dialing.
// If no peer is found, or all connection slots are full, it blocks until one
// becomes available. The caller must call Dialed() or DialFailed() for the
// returned peer.
func (m *PeerManager) DialNext(ctx context.Context) (NodeAddress, error) {
for {
address, err := m.TryDialNext()
if err != nil || (address != NodeAddress{}) {
return address, err
}
select {
case <-m.dialWaker.Sleep():
case <-ctx.Done():
return NodeAddress{}, ctx.Err()
}
}
}
// TryDialNext is equivalent to DialNext(), but immediately returns an empty
// address if no peers or connection slots are available.
func (m *PeerManager) TryDialNext() (NodeAddress, error) {
m.mtx.Lock()
defer m.mtx.Unlock()
// We allow dialing MaxConnected+MaxConnectedUpgrade peers. Including
// MaxConnectedUpgrade allows us to probe additional peers that have a
// higher score than any other peers, and if successful evict it.
if m.options.MaxConnected > 0 && m.NumConnected()+len(m.dialing) >=
int(m.options.MaxConnected)+int(m.options.MaxConnectedUpgrade) {
return NodeAddress{}, nil
}
for _, peer := range m.store.Ranked() {
if m.dialing[peer.ID] || m.connected[peer.ID] {
continue
}
for _, addressInfo := range peer.AddressInfo {
if time.Since(addressInfo.LastDialFailure) < m.retryDelay(addressInfo.DialFailures, peer.Persistent) {
continue
}
// We now have an eligible address to dial. If we're full but have
// upgrade capacity (as checked above), we find a lower-scored peer
// we can replace and mark it as upgrading so noone else claims it.
//
// If we don't find one, there is no point in trying additional
// peers, since they will all have the same or lower score than this
// peer (since they're ordered by score via peerStore.Ranked).
if m.options.MaxConnected > 0 && m.NumConnected() >= int(m.options.MaxConnected) {
upgradeFromPeer := m.findUpgradeCandidate(peer.ID, peer.Score())
if upgradeFromPeer == "" {
return NodeAddress{}, nil
}
m.upgrading[upgradeFromPeer] = peer.ID
}
m.dialing[peer.ID] = true
return addressInfo.Address, nil
}
}
return NodeAddress{}, nil
}
// DialFailed reports a failed dial attempt. This will make the peer available
// for dialing again when appropriate (possibly after a retry timeout).
func (m *PeerManager) DialFailed(ctx context.Context, address NodeAddress) error {
m.mtx.Lock()
defer m.mtx.Unlock()
delete(m.dialing, address.NodeID)
for from, to := range m.upgrading {
if to == address.NodeID {
delete(m.upgrading, from) // Unmark failed upgrade attempt.
}
}
peer, ok := m.store.Get(address.NodeID)
if !ok { // Peer may have been removed while dialing, ignore.
return nil
}
addressInfo, ok := peer.AddressInfo[address]
if !ok {
return nil // Assume the address has been removed, ignore.
}
addressInfo.LastDialFailure = time.Now().UTC()
addressInfo.DialFailures++
// We need to invalidate the cache after score changed
m.store.ranked = nil
if err := m.store.Set(peer); err != nil {
return err
}
// We spawn a goroutine that notifies DialNext() again when the retry
// timeout has elapsed, so that we can consider dialing it again. We
// calculate the retry delay outside the goroutine, since it must hold
// the mutex lock.
if d := m.retryDelay(addressInfo.DialFailures, peer.Persistent); d != 0 && d != retryNever {
if d == m.options.MaxRetryTime {
if err := m.store.Delete(address.NodeID); err != nil {
return err
}
return fmt.Errorf("dialing failed %d times will not retry for address=%s, deleting peer", addressInfo.DialFailures, address.NodeID)
}
go func() {
// Use an explicit timer with deferred cleanup instead of
// time.After(), to avoid leaking goroutines on PeerManager.Close().
timer := time.NewTimer(d)
defer timer.Stop()
select {
case <-timer.C:
m.dialWaker.Wake()
case <-ctx.Done():
}
}()
} else {
m.dialWaker.Wake()
}
return nil
}
// Dialed marks a peer as successfully dialed. Any further connections will be
// rejected, and once disconnected the peer may be dialed again.
func (m *PeerManager) Dialed(address NodeAddress) error {
m.mtx.Lock()
defer m.mtx.Unlock()
delete(m.dialing, address.NodeID)
var upgradeFromPeer types.NodeID
for from, to := range m.upgrading {
if to == address.NodeID {
delete(m.upgrading, from)
upgradeFromPeer = from
// Don't break, just in case this peer was marked as upgrading for
// multiple lower-scored peers (shouldn't really happen).
}
}
if address.NodeID == m.selfID {
return fmt.Errorf("rejecting connection to self (%v)", address.NodeID)
}
if m.connected[address.NodeID] {
dupeConnectionErr := fmt.Errorf("cant dial, peer=%q is already connected", address.NodeID)
return dupeConnectionErr
}
if m.options.MaxConnected > 0 && m.NumConnected() >= int(m.options.MaxConnected) {
if upgradeFromPeer == "" || m.NumConnected() >=
int(m.options.MaxConnected)+int(m.options.MaxConnectedUpgrade) {
return fmt.Errorf("already connected to maximum number of peers")
}
}
peer, ok := m.store.Get(address.NodeID)
if !ok {
return fmt.Errorf("peer %q was removed while dialing", address.NodeID)
}
now := time.Now().UTC()
peer.LastConnected = now
if addressInfo, ok := peer.AddressInfo[address]; ok {
addressInfo.DialFailures = 0
addressInfo.LastDialSuccess = now
// If not found, assume address has been removed.
}
if err := m.store.Set(peer); err != nil {
return err
}
if upgradeFromPeer != "" && m.options.MaxConnected > 0 &&
m.NumConnected() >= int(m.options.MaxConnected) {
// Look for an even lower-scored peer that may have appeared since we
// started the upgrade.
if p, ok := m.store.Get(upgradeFromPeer); ok {
if u := m.findUpgradeCandidate(p.ID, p.Score()); u != "" {
upgradeFromPeer = u
}
}
m.evict[upgradeFromPeer] = true
}
m.connected[peer.ID] = true
m.evictWaker.Wake()
return nil
}
// Accepted marks an incoming peer connection successfully accepted. If the peer
// is already connected or we don't allow additional connections then this will
// return an error.
//
// If full but MaxConnectedUpgrade is non-zero and the incoming peer is
// better-scored than any existing peers, then we accept it and evict a
// lower-scored peer.
//
// NOTE: We can't take an address here, since e.g. TCP uses a different port
// number for outbound traffic than inbound traffic, so the peer's endpoint
// wouldn't necessarily be an appropriate address to dial.
//
// FIXME: When we accept a connection from a peer, we should register that
// peer's address in the peer store so that we can dial it later. In order to do
// that, we'll need to get the remote address after all, but as noted above that
// can't be the remote endpoint since that will usually have the wrong port
// number.
func (m *PeerManager) Accepted(peerID types.NodeID) error {
m.mtx.Lock()
defer m.mtx.Unlock()
if peerID == m.selfID {
return fmt.Errorf("rejecting connection from self (%v)", peerID)
}
if m.connected[peerID] {
dupeConnectionErr := fmt.Errorf("can't accept, peer=%q is already connected", peerID)
return dupeConnectionErr
}
if m.options.MaxConnected > 0 &&
m.NumConnected() >= int(m.options.MaxConnected)+int(m.options.MaxConnectedUpgrade) {
return fmt.Errorf("already connected to maximum number of peers")
}
peer, ok := m.store.Get(peerID)
if !ok {
peer = m.newPeerInfo(peerID)
}
// reset this to avoid penalizing peers for their past transgressions
for _, addr := range peer.AddressInfo {
addr.DialFailures = 0
}
// If all connections slots are full, but we allow upgrades (and we checked
// above that we have upgrade capacity), then we can look for a lower-scored
// peer to replace and if found accept the connection anyway and evict it.
var upgradeFromPeer types.NodeID
if m.options.MaxConnected > 0 && m.NumConnected() >= int(m.options.MaxConnected) {
upgradeFromPeer = m.findUpgradeCandidate(peer.ID, peer.Score())
if upgradeFromPeer == "" {
return fmt.Errorf("already connected to maximum number of peers")
}
}
peer.LastConnected = time.Now().UTC()
if err := m.store.Set(peer); err != nil {
return err
}
m.connected[peerID] = true
if upgradeFromPeer != "" {
m.evict[upgradeFromPeer] = true
}
m.evictWaker.Wake()
return nil
}
// Ready marks a peer as ready, broadcasting status updates to
// subscribers. The peer must already be marked as connected. This is
// separate from Dialed() and Accepted() to allow the router to set up
// its internal queues before reactors start sending messages. The
// channels set here are passed in the peer update broadcast to
// reactors, which can then mediate their own behavior based on the
// capability of the peers.
func (m *PeerManager) Ready(ctx context.Context, peerID types.NodeID, channels ChannelIDSet) {
m.mtx.Lock()
defer m.mtx.Unlock()
if m.connected[peerID] {
m.ready[peerID] = true
m.broadcast(ctx, PeerUpdate{
NodeID: peerID,
Status: PeerStatusUp,
Channels: channels,
})
}
}
// EvictNext returns the next peer to evict (i.e. disconnect). If no evictable
// peers are found, the call will block until one becomes available.
func (m *PeerManager) EvictNext(ctx context.Context) (types.NodeID, error) {
for {
id, err := m.TryEvictNext()
if err != nil || id != "" {
return id, err
}
select {
case <-m.evictWaker.Sleep():
case <-ctx.Done():
return "", ctx.Err()
}
}
}
// TryEvictNext is equivalent to EvictNext, but immediately returns an empty
// node ID if no evictable peers are found.
func (m *PeerManager) TryEvictNext() (types.NodeID, error) {
m.mtx.Lock()
defer m.mtx.Unlock()
// If any connected peers are explicitly scheduled for eviction, we return a
// random one.
for peerID := range m.evict {
delete(m.evict, peerID)
if m.connected[peerID] && !m.evicting[peerID] {
m.evicting[peerID] = true
return peerID, nil
}
}
// If we're below capacity, we don't need to evict anything.
if m.options.MaxConnected == 0 ||
m.NumConnected()-len(m.evicting) <= int(m.options.MaxConnected) {
return "", nil
}
// If we're above capacity (shouldn't really happen), just pick the
// lowest-ranked peer to evict.
ranked := m.store.Ranked()
for i := len(ranked) - 1; i >= 0; i-- {
peer := ranked[i]
if m.connected[peer.ID] && !m.evicting[peer.ID] {
m.evicting[peer.ID] = true
return peer.ID, nil
}
}
return "", nil
}
// Disconnected unmarks a peer as connected, allowing it to be dialed or
// accepted again as appropriate.
func (m *PeerManager) Disconnected(ctx context.Context, peerID types.NodeID) {
m.mtx.Lock()
defer m.mtx.Unlock()
// Update score and invalidate cache if a peer got disconnected
if _, ok := m.store.peers[peerID]; ok {
m.store.peers[peerID].NumOfDisconnections++
m.store.ranked = nil
}
ready := m.ready[peerID]
delete(m.connected, peerID)
delete(m.upgrading, peerID)
delete(m.evict, peerID)
delete(m.evicting, peerID)
delete(m.ready, peerID)
if ready {
m.broadcast(ctx, PeerUpdate{
NodeID: peerID,
Status: PeerStatusDown,
})
}
m.dialWaker.Wake()
}
// Errored reports a peer error, causing the peer to be evicted if it's
// currently connected.
//
// FIXME: This should probably be replaced with a peer behavior API, see
// PeerError comments for more details.
//
// FIXME: This will cause the peer manager to immediately try to reconnect to
// the peer, which is probably not always what we want.
func (m *PeerManager) Errored(peerID types.NodeID, err error) {
m.mtx.Lock()
defer m.mtx.Unlock()
if m.connected[peerID] {
m.evict[peerID] = true
}
m.evictWaker.Wake()
}
// Advertise returns a list of peer addresses to advertise to a peer.
//
// FIXME: This is fairly naïve and only returns the addresses of the
// highest-ranked peers.
func (m *PeerManager) Advertise(peerID types.NodeID, limit uint16) []NodeAddress {
m.mtx.Lock()
defer m.mtx.Unlock()
addresses := make([]NodeAddress, 0, limit)
// advertise ourselves, to let everyone know how to dial us back
// and enable mutual address discovery
if m.options.SelfAddress.Hostname != "" && m.options.SelfAddress.Port != 0 {
addresses = append(addresses, m.options.SelfAddress)
}
for _, peer := range m.store.Ranked() {
if peer.ID == peerID {
continue
}
for nodeAddr, addressInfo := range peer.AddressInfo {
if len(addresses) >= int(limit) {
return addresses
}
// only add non-private NodeIDs
if _, ok := m.options.PrivatePeers[nodeAddr.NodeID]; !ok {
addresses = append(addresses, addressInfo.Address)
}
}
}
return addresses
}
func (m *PeerManager) NumConnected() int {
cnt := 0
for peer := range m.connected {
if !m.options.isUnconditional(peer) {
cnt++
}
}
return cnt
}
// PeerEventSubscriber describes the type of the subscription method, to assist
// in isolating reactors specific construction and lifecycle from the
// peer manager.
type PeerEventSubscriber func(context.Context) *PeerUpdates
// Subscribe subscribes to peer updates. The caller must consume the peer
// updates in a timely fashion and close the subscription when done, otherwise
// the PeerManager will halt.
func (m *PeerManager) Subscribe(ctx context.Context) *PeerUpdates {
// FIXME: We use a size 1 buffer here. When we broadcast a peer update
// we have to loop over all of the subscriptions, and we want to avoid
// having to block and wait for a context switch before continuing on
// to the next subscriptions. This also prevents tail latencies from
// compounding. Limiting it to 1 means that the subscribers are still
// reasonably in sync. However, this should probably be benchmarked.
peerUpdates := NewPeerUpdates(make(chan PeerUpdate, 1), 1)
m.Register(ctx, peerUpdates)
return peerUpdates
}
// Register allows you to inject a custom PeerUpdate instance into the
// PeerManager, rather than relying on the instance constructed by the
// Subscribe method, which wraps the functionality of the Register
// method.
//
// The caller must consume the peer updates from this PeerUpdates
// instance in a timely fashion and close the subscription when done,
// otherwise the PeerManager will halt.
func (m *PeerManager) Register(ctx context.Context, peerUpdates *PeerUpdates) {
m.mtx.Lock()
defer m.mtx.Unlock()
m.subscriptions[peerUpdates] = peerUpdates
go func() {
for {
select {
case <-ctx.Done():
return
case pu := <-peerUpdates.routerUpdatesCh:
m.processPeerEvent(ctx, pu)
}
}
}()
go func() {
<-ctx.Done()
m.mtx.Lock()
defer m.mtx.Unlock()
delete(m.subscriptions, peerUpdates)
}()
}
func (m *PeerManager) processPeerEvent(ctx context.Context, pu PeerUpdate) {
m.mtx.Lock()
defer m.mtx.Unlock()
if ctx.Err() != nil {
return
}
if _, ok := m.store.peers[pu.NodeID]; !ok {
m.store.peers[pu.NodeID] = &peerInfo{}
}
switch pu.Status {
case PeerStatusBad:
m.store.peers[pu.NodeID].MutableScore--