forked from algorand/go-algorand
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wsNetwork.go
1762 lines (1565 loc) · 61.5 KB
/
wsNetwork.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
// Copyright (C) 2019 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand. If not, see <https://www.gnu.org/licenses/>.
package network
import (
"container/heap"
"context"
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
"math"
"math/rand"
"net"
"net/http"
"net/url"
"path"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/algorand/go-deadlock"
"github.com/algorand/websocket"
"github.com/gorilla/mux"
"golang.org/x/net/netutil"
"golang.org/x/sys/unix"
"github.com/algorand/go-algorand/config"
"github.com/algorand/go-algorand/crypto"
"github.com/algorand/go-algorand/logging"
"github.com/algorand/go-algorand/logging/telemetryspec"
"github.com/algorand/go-algorand/protocol"
tools_network "github.com/algorand/go-algorand/tools/network"
"github.com/algorand/go-algorand/util/metrics"
)
const incomingThreads = 20
const broadcastThreads = 4
const messageFilterSize = 5000 // messages greater than that size may be blocked by incoming/outgoing filter
// httpServerReadHeaderTimeout is the amount of time allowed to read
// request headers. The connection's read deadline is reset
// after reading the headers and the Handler can decide what
// is considered too slow for the body.
const httpServerReadHeaderTimeout = time.Second * 10
// httpServerWriteTimeout is the maximum duration before timing out
// writes of the response. It is reset whenever a new
// request's header is read.
const httpServerWriteTimeout = time.Second * 60
// httpServerIdleTimeout is the maximum amount of time to wait for the
// next request when keep-alives are enabled. If httpServerIdleTimeout
// is zero, the value of ReadTimeout is used. If both are
// zero, ReadHeaderTimeout is used.
const httpServerIdleTimeout = time.Second * 4
// MaxHeaderBytes controls the maximum number of bytes the
// server will read parsing the request header's keys and
// values, including the request line. It does not limit the
// size of the request body.
const httpServerMaxHeaderBytes = 4096
// MaxInt is the maximum int which might be int32 or int64
const MaxInt = int((^uint(0)) >> 1)
// connectionActivityMonitorInterval is the interval at which we check
// if any of the connected peers have been idle for a long while and
// need to be disconnected.
const connectionActivityMonitorInterval = 3 * time.Minute
// maxPeerInactivityDuration is the maximum allowed duration for a
// peer to remain completly idle (i.e. no inbound or outbound communication), before
// we discard the connection.
const maxPeerInactivityDuration = 5 * time.Minute
// maxMessageQueueDuration is the maximum amount of time a message is allowed to be waiting
// in the various queues before being sent. Once that deadline has reached, sending the message
// is pointless, as it's too stale to be of any value
const maxMessageQueueDuration = 25 * time.Second
// slowWritingPeerMonitorInterval is the interval at which we peek on the connected peers to
// verify that their current outgoing message is not being blocked for too long.
const slowWritingPeerMonitorInterval = 5 * time.Second
var networkIncomingConnections = metrics.MakeGauge(metrics.NetworkIncomingConnections)
var networkOutgoingConnections = metrics.MakeGauge(metrics.NetworkOutgoingConnections)
var networkIncomingBufferMicros = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_rx_buffer_micros_total", Description: "microseconds spent by incoming messages on the receive buffer"})
var networkHandleMicros = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_rx_handle_micros_total", Description: "microseconds spent by protocol handlers in the receive thread"})
var networkBroadcasts = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_broadcasts_total", Description: "number of broadcast operations"})
var networkBroadcastQueueMicros = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_broadcast_queue_micros_total", Description: "microseconds broadcast requests sit on queue"})
var networkBroadcastSendMicros = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_broadcast_send_micros_total", Description: "microseconds spent broadcasting"})
var networkBroadcastsDropped = metrics.MakeCounter(metrics.MetricName{Name: "algod_broadcasts_dropped_total", Description: "number of broadcast messages not sent to any peer"})
var networkPeerBroadcastDropped = metrics.MakeCounter(metrics.MetricName{Name: "algod_peer_broadcast_dropped_total", Description: "number of broadcast messages not sent to some peer"})
var networkSlowPeerDrops = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_slow_drops_total", Description: "number of peers dropped for being slow to send to"})
var networkIdlePeerDrops = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_idle_drops_total", Description: "number of peers dropped due to idle connection"})
var networkBroadcastQueueFull = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_broadcast_queue_full_total", Description: "number of messages that were drops due to full broadcast queue"})
var minPing = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_peer_min_ping_seconds", Description: "Network round trip time to fastest peer in seconds."})
var meanPing = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_peer_mean_ping_seconds", Description: "Network round trip time to average peer in seconds."})
var medianPing = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_peer_median_ping_seconds", Description: "Network round trip time to median peer in seconds."})
var maxPing = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_peer_max_ping_seconds", Description: "Network round trip time to slowest peer in seconds."})
var peers = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_peers", Description: "Number of active peers."})
var incomingPeers = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_incoming_peers", Description: "Number of active incoming peers."})
var outgoingPeers = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_outgoing_peers", Description: "Number of active outgoing peers."})
// Peer opaque interface for referring to a neighbor in the network
type Peer interface{}
// PeerOption allows users to specify a subset of peers to query
type PeerOption int
const (
// PeersConnectedOut specifies all peers with outgoing connections
PeersConnectedOut PeerOption = iota
// PeersConnectedIn specifies all peers with inbound connections
PeersConnectedIn PeerOption = iota
// PeersPhonebook specifies all peers in the phonebook
PeersPhonebook PeerOption = iota
)
// GossipNode represents a node in the gossip network
type GossipNode interface {
Address() (string, bool)
Broadcast(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error
Relay(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error
Disconnect(badnode Peer)
DisconnectPeers()
Ready() chan struct{}
// RegisterHTTPHandler path accepts gorilla/mux path annotations
RegisterHTTPHandler(path string, handler http.Handler)
// RequestConnectOutgoing asks the system to actually connect to peers.
// `replace` optionally drops existing connections before making new ones.
// `quit` chan allows cancellation. TODO: use `context`
RequestConnectOutgoing(replace bool, quit <-chan struct{})
// Get a list of Peers we could potentially send a direct message to.
GetPeers(options ...PeerOption) []Peer
// Start threads, listen on sockets.
Start()
// Close sockets. Stop threads.
Stop()
// RegisterHandlers adds to the set of given message handlers.
RegisterHandlers(dispatch []TaggedMessageHandler)
// ClearHandlers deregisters all the existing message handlers.
ClearHandlers()
}
// IncomingMessage represents a message arriving from some peer in our p2p network
type IncomingMessage struct {
Sender Peer
Tag Tag
Data []byte
Err error
Net GossipNode
// Received is time.Time.UnixNano()
Received int64
// processing is a channel that is used by messageHandlerThread
// to indicate that it has started processing this message. It
// is used to ensure fairness across peers in terms of processing
// messages.
processing chan struct{}
}
// Tag is a short string (2 bytes) marking a type of message
type Tag = protocol.Tag
func highPriorityTag(tag protocol.Tag) bool {
return tag == protocol.AgreementVoteTag || tag == protocol.ProposalPayloadTag
}
// OutgoingMessage represents a message we want to send.
type OutgoingMessage struct {
Action ForwardingPolicy
Tag Tag
Payload []byte
}
// ForwardingPolicy is an enum indicating to whom we should send a message
type ForwardingPolicy int
const (
// Ignore - discard (don't forward)
Ignore ForwardingPolicy = iota
// Disconnect - disconnect from the peer that sent this message
Disconnect
// Broadcast - forward to everyone (except the sender)
Broadcast
)
// MessageHandler takes a IncomingMessage (e.g., vote, transaction), processes it, and returns what (if anything)
// to send to the network in response.
// The ForwardingPolicy field of the returned OutgoingMessage indicates whether to reply directly to the sender
// (unicast), propagate to everyone except the sender (broadcast), or do nothing (ignore).
type MessageHandler interface {
Handle(message IncomingMessage) OutgoingMessage
}
// HandlerFunc represents an implemenation of the MessageHandler interface
type HandlerFunc func(message IncomingMessage) OutgoingMessage
// Handle implements MessageHandler.Handle, calling the handler with the IncomingKessage and returning the OutgoingMessage
func (f HandlerFunc) Handle(message IncomingMessage) OutgoingMessage {
return f(message)
}
// TaggedMessageHandler receives one type of broadcast messages
type TaggedMessageHandler struct {
Tag
MessageHandler
}
// Propagate is a convenience function to save typing in the common case of a message handler telling us to propagate an incoming message
// "return network.Propagate(msg)" instead of "return network.OutgoingMsg{network.Broadcast, msg.Tag, msg.Data}"
func Propagate(msg IncomingMessage) OutgoingMessage {
return OutgoingMessage{Broadcast, msg.Tag, msg.Data}
}
// GossipNetworkPath is the URL path to connect to the websocket gossip node at.
// Contains {genesisID} param to be handled by gorilla/mux
const GossipNetworkPath = "/v1/{genesisID}/gossip"
// WebsocketNetwork implements GossipNode
type WebsocketNetwork struct {
listener net.Listener
server http.Server
router *mux.Router
scheme string // are we serving http or https ?
upgrader websocket.Upgrader
config config.Local
log logging.Logger
readBuffer chan IncomingMessage
wg sync.WaitGroup
handlers Multiplexer
ctx context.Context
ctxCancel context.CancelFunc
peersLock deadlock.RWMutex
peers []*wsPeer
broadcastQueueHighPrio chan broadcastRequest
broadcastQueueBulk chan broadcastRequest
phonebook *MultiPhonebook
GenesisID string
NetworkID protocol.NetworkID
RandomID string
ready int32
readyChan chan struct{}
meshUpdateRequests chan meshRequest
// Keep a record of pending outgoing connections so
// we don't start duplicates connection attempts.
// Needs to be locked because it's accessed from the
// meshThread and also threads started to run tryConnect()
tryConnectAddrs map[string]int64
tryConnectLock deadlock.Mutex
incomingMsgFilter *messageFilter // message filter to remove duplicate incoming messages from different peers
eventualReadyDelay time.Duration
relayMessages bool // True if we should relay messages from other nodes (nominally true for relays, false otherwise)
prioScheme NetPrioScheme
prioTracker *prioTracker
prioResponseChan chan *wsPeer
// outgoingMessagesBufferSize is the size used for outgoing messages.
outgoingMessagesBufferSize int
// slowWritingPeerMonitorInterval defines the interval between two consecutive tests for slow peer writing
slowWritingPeerMonitorInterval time.Duration
requestsTracker *RequestTracker
requestsLogger *RequestLogger
}
type broadcastRequest struct {
tag Tag
data []byte
except *wsPeer
done chan struct{}
enqueueTime time.Time
}
// Address returns a string and whether that is a 'final' address or guessed.
// Part of GossipNode interface
func (wn *WebsocketNetwork) Address() (string, bool) {
parsedURL := url.URL{Scheme: wn.scheme}
var connected bool
if wn.listener == nil {
parsedURL.Host = wn.config.NetAddress
connected = false
} else {
parsedURL.Host = wn.listener.Addr().String()
connected = true
}
return parsedURL.String(), connected
}
// PublicAddress what we tell other nodes to connect to.
// Might be different than our locally percieved network address due to NAT/etc.
// Returns config "PublicAddress" if available, otherwise local addr.
func (wn *WebsocketNetwork) PublicAddress() string {
if len(wn.config.PublicAddress) > 0 {
return wn.config.PublicAddress
}
localAddr, _ := wn.Address()
return localAddr
}
// Broadcast sends a message.
// If except is not nil then we will not send it to that neighboring Peer.
// if wait is true then the call blocks until the packet has actually been sent to all neighbors.
// TODO: add `priority` argument so that we don't have to guess it based on tag
func (wn *WebsocketNetwork) Broadcast(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error {
request := broadcastRequest{tag: tag, data: data, enqueueTime: time.Now()}
if except != nil {
request.except = except.(*wsPeer)
}
broadcastQueue := wn.broadcastQueueBulk
if highPriorityTag(tag) {
broadcastQueue = wn.broadcastQueueHighPrio
}
if wait {
request.done = make(chan struct{})
select {
case broadcastQueue <- request:
// ok, enqueued
//wn.log.Debugf("broadcast enqueued")
case <-wn.ctx.Done():
return errNetworkClosing
case <-ctx.Done():
return errBcastCallerCancel
}
select {
case <-request.done:
//wn.log.Debugf("broadcast done")
return nil
case <-wn.ctx.Done():
return errNetworkClosing
case <-ctx.Done():
return errBcastCallerCancel
}
}
// no wait
select {
case broadcastQueue <- request:
//wn.log.Debugf("broadcast enqueued nowait")
return nil
default:
wn.log.Debugf("broadcast queue full")
// broadcastQueue full, and we're not going to wait for it.
networkBroadcastQueueFull.Inc(nil)
return errBcastQFull
}
}
// Relay message
func (wn *WebsocketNetwork) Relay(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error {
if wn.relayMessages {
return wn.Broadcast(ctx, tag, data, wait, except)
}
return nil
}
func (wn *WebsocketNetwork) disconnectThread(badnode Peer, reason disconnectReason) {
defer wn.wg.Done()
wn.disconnect(badnode, reason)
}
// Disconnect from a peer, probably due to protocol errors.
func (wn *WebsocketNetwork) Disconnect(node Peer) {
wn.disconnect(node, disconnectBadData)
}
// Disconnect from a peer, probably due to protocol errors.
func (wn *WebsocketNetwork) disconnect(badnode Peer, reason disconnectReason) {
if badnode == nil {
return
}
peer := badnode.(*wsPeer)
peer.CloseAndWait()
wn.removePeer(peer, reason)
}
func closeWaiter(wg *sync.WaitGroup, peer *wsPeer) {
defer wg.Done()
peer.CloseAndWait()
}
// DisconnectPeers shuts down all connections
func (wn *WebsocketNetwork) DisconnectPeers() {
wn.peersLock.Lock()
defer wn.peersLock.Unlock()
closeGroup := sync.WaitGroup{}
closeGroup.Add(len(wn.peers))
for _, peer := range wn.peers {
go closeWaiter(&closeGroup, peer)
}
wn.peers = wn.peers[:0]
closeGroup.Wait()
}
// Ready returns a chan that will be closed when we have a minimum number of peer connections active
func (wn *WebsocketNetwork) Ready() chan struct{} {
return wn.readyChan
}
// RegisterHTTPHandler path accepts gorilla/mux path annotations
func (wn *WebsocketNetwork) RegisterHTTPHandler(path string, handler http.Handler) {
wn.router.Handle(path, handler)
}
// RequestConnectOutgoing tries to actually do the connect to new peers.
// `replace` drop all connections first and find new peers.
func (wn *WebsocketNetwork) RequestConnectOutgoing(replace bool, quit <-chan struct{}) {
request := meshRequest{disconnect: false}
if quit != nil {
request.done = make(chan struct{})
}
select {
case wn.meshUpdateRequests <- request:
case <-quit:
return
}
if request.done != nil {
select {
case <-request.done:
case <-quit:
}
}
}
// GetPeers returns a snapshot of our Peer list, according to the specified options.
// Peers may be duplicated and refer to the same underlying node.
func (wn *WebsocketNetwork) GetPeers(options ...PeerOption) []Peer {
outPeers := make([]Peer, 0)
for _, option := range options {
switch option {
case PeersConnectedOut:
wn.peersLock.RLock()
for _, peer := range wn.peers {
if peer.outgoing {
outPeers = append(outPeers, Peer(peer))
}
}
wn.peersLock.RUnlock()
case PeersPhonebook:
// return copy of phonebook, which probably also contains peers we're connected to, but if it doesn't maybe we shouldn't be making new connections to those peers (because they disappeared from the directory)
var addrs []string
addrs = wn.phonebook.GetAddresses(1000)
for _, addr := range addrs {
outPeers = append(outPeers, &wsPeerCore{net: wn, rootURL: addr})
}
case PeersConnectedIn:
wn.peersLock.RLock()
for _, peer := range wn.peers {
if !peer.outgoing {
outPeers = append(outPeers, Peer(peer))
}
}
wn.peersLock.RUnlock()
}
}
return outPeers
}
func (wn *WebsocketNetwork) setup() {
wn.upgrader.ReadBufferSize = 4096
wn.upgrader.WriteBufferSize = 4096
wn.upgrader.EnableCompression = false
wn.router = mux.NewRouter()
wn.router.Handle(GossipNetworkPath, wn)
wn.requestsTracker = makeRequestsTracker(wn.router, wn.log, wn.config)
if wn.config.EnableRequestLogger {
wn.requestsLogger = makeRequestLogger(wn.requestsTracker, wn.log)
wn.server.Handler = wn.requestsLogger
} else {
wn.server.Handler = wn.requestsTracker
}
wn.server.ReadHeaderTimeout = httpServerReadHeaderTimeout
wn.server.WriteTimeout = httpServerWriteTimeout
wn.server.IdleTimeout = httpServerIdleTimeout
wn.server.MaxHeaderBytes = httpServerMaxHeaderBytes
wn.ctx, wn.ctxCancel = context.WithCancel(context.Background())
wn.relayMessages = wn.config.NetAddress != "" || wn.config.ForceRelayMessages
// roughly estimate the number of messages that could be sent over the lifespan of a single round.
wn.outgoingMessagesBufferSize = int(config.Consensus[protocol.ConsensusCurrentVersion].NumProposers*2 +
config.Consensus[protocol.ConsensusCurrentVersion].SoftCommitteeSize +
config.Consensus[protocol.ConsensusCurrentVersion].CertCommitteeSize +
config.Consensus[protocol.ConsensusCurrentVersion].NextCommitteeSize +
config.Consensus[protocol.ConsensusCurrentVersion].LateCommitteeSize +
config.Consensus[protocol.ConsensusCurrentVersion].RedoCommitteeSize +
config.Consensus[protocol.ConsensusCurrentVersion].DownCommitteeSize)
wn.broadcastQueueHighPrio = make(chan broadcastRequest, wn.outgoingMessagesBufferSize)
wn.broadcastQueueBulk = make(chan broadcastRequest, 100)
wn.meshUpdateRequests = make(chan meshRequest, 5)
wn.readyChan = make(chan struct{})
wn.tryConnectAddrs = make(map[string]int64)
wn.eventualReadyDelay = time.Minute
wn.prioTracker = newPrioTracker(wn)
if wn.slowWritingPeerMonitorInterval == 0 {
wn.slowWritingPeerMonitorInterval = slowWritingPeerMonitorInterval
}
readBufferLen := wn.config.IncomingConnectionsLimit + wn.config.GossipFanout
if readBufferLen < 100 {
readBufferLen = 100
}
if readBufferLen > 10000 {
readBufferLen = 10000
}
wn.readBuffer = make(chan IncomingMessage, readBufferLen)
var rbytes [10]byte
rand.Read(rbytes[:])
wn.RandomID = base64.StdEncoding.EncodeToString(rbytes[:])
if wn.config.EnableIncomingMessageFilter {
wn.incomingMsgFilter = makeMessageFilter(wn.config.IncomingMessageFilterBucketCount, wn.config.IncomingMessageFilterBucketSize)
}
}
func (wn *WebsocketNetwork) rlimitIncomingConnections() error {
var lim unix.Rlimit
err := unix.Getrlimit(unix.RLIMIT_NOFILE, &lim)
if err != nil {
return err
}
// If rlim_max is not sufficient, reduce IncomingConnectionsLimit
var rlimitMaxCap uint64
if lim.Max < wn.config.ReservedFDs {
rlimitMaxCap = 0
} else {
rlimitMaxCap = lim.Max - wn.config.ReservedFDs
}
if rlimitMaxCap > uint64(MaxInt) {
rlimitMaxCap = uint64(MaxInt)
}
if wn.config.IncomingConnectionsLimit > int(rlimitMaxCap) {
wn.log.Warnf("Reducing IncomingConnectionsLimit from %d to %d since RLIMIT_NOFILE is %d",
wn.config.IncomingConnectionsLimit, rlimitMaxCap, lim.Max)
wn.config.IncomingConnectionsLimit = int(rlimitMaxCap)
}
// Set rlim_cur to match IncomingConnectionsLimit
newLimit := uint64(wn.config.IncomingConnectionsLimit) + wn.config.ReservedFDs
if newLimit > lim.Cur {
if runtime.GOOS == "darwin" && newLimit > 10240 && lim.Max == 0x7fffffffffffffff {
// The max file limit is 10240, even though
// the max returned by Getrlimit is 1<<63-1.
// This is OPEN_MAX in sys/syslimits.h.
// see https://github.com/golang/go/issues/30401
newLimit = 10240
}
lim.Cur = newLimit
err = unix.Setrlimit(unix.RLIMIT_NOFILE, &lim)
if err != nil {
return err
}
}
return nil
}
// Start makes network connections and threads
func (wn *WebsocketNetwork) Start() {
var err error
if wn.config.IncomingConnectionsLimit < 0 {
wn.config.IncomingConnectionsLimit = MaxInt
}
// Make sure we do not accept more incoming connections than our
// open file rlimit, with some headroom for other FDs (DNS, log
// files, SQLite files, telemetry, ...)
err = wn.rlimitIncomingConnections()
if err != nil {
wn.log.Error("ws network start: rlimitIncomingConnections ", err)
return
}
if wn.config.NetAddress != "" {
listener, err := net.Listen("tcp", wn.config.NetAddress)
if err != nil {
wn.log.Errorf("network could not listen %v: %s", wn.config.NetAddress, err)
return
}
// wrap the original listener with a limited connection listener
listener = netutil.LimitListener(listener, wn.config.IncomingConnectionsLimit)
// wrap the limited connection listener with a requests tracker listener
wn.listener = wn.requestsTracker.Listener(listener)
wn.log.Debugf("listening on %s", wn.listener.Addr().String())
}
if wn.config.TLSCertFile != "" && wn.config.TLSKeyFile != "" {
wn.scheme = "https"
} else {
wn.scheme = "http"
}
wn.meshUpdateRequests <- meshRequest{false, nil}
wn.RegisterHandlers(pingHandlers)
wn.RegisterHandlers(prioHandlers)
if wn.listener != nil {
wn.wg.Add(1)
go wn.httpdThread()
}
wn.wg.Add(1)
go wn.meshThread()
if wn.config.PeerPingPeriodSeconds > 0 {
wn.wg.Add(1)
go wn.pingThread()
}
for i := 0; i < incomingThreads; i++ {
wn.wg.Add(1)
go wn.messageHandlerThread()
}
for i := 0; i < broadcastThreads; i++ {
wn.wg.Add(1)
go wn.broadcastThread()
}
wn.wg.Add(1)
go wn.prioWeightRefresh()
wn.log.Infof("serving genesisID=%s on %#v with RandomID=%s", wn.GenesisID, wn.PublicAddress(), wn.RandomID)
}
func (wn *WebsocketNetwork) httpdThread() {
defer wn.wg.Done()
var err error
if wn.config.TLSCertFile != "" && wn.config.TLSKeyFile != "" {
err = wn.server.ServeTLS(wn.listener, wn.config.TLSCertFile, wn.config.TLSKeyFile)
} else {
err = wn.server.Serve(wn.listener)
}
if err == http.ErrServerClosed {
} else if err != nil {
wn.log.Info("ws net http server exited ", err)
}
}
// innerStop context for shutting down peers
func (wn *WebsocketNetwork) innerStop() {
wn.peersLock.Lock()
defer wn.peersLock.Unlock()
wn.wg.Add(len(wn.peers))
for _, peer := range wn.peers {
go closeWaiter(&wn.wg, peer)
}
wn.peers = wn.peers[:0]
}
// Stop closes network connections and stops threads.
// Stop blocks until all activity on this node is done.
func (wn *WebsocketNetwork) Stop() {
wn.innerStop()
var listenAddr string
if wn.listener != nil {
listenAddr = wn.listener.Addr().String()
}
wn.ctxCancel()
ctx, timeoutCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer timeoutCancel()
err := wn.server.Shutdown(ctx)
if err != nil {
wn.log.Warnf("problem shutting down %s: %v", listenAddr, err)
}
wn.wg.Wait()
if wn.listener != nil {
wn.log.Debugf("closed %s", listenAddr)
}
}
// RegisterHandlers registers the set of given message handlers.
func (wn *WebsocketNetwork) RegisterHandlers(dispatch []TaggedMessageHandler) {
wn.handlers.RegisterHandlers(dispatch)
}
// ClearHandlers deregisters all the existing message handlers.
func (wn *WebsocketNetwork) ClearHandlers() {
wn.handlers.ClearHandlers()
}
func (wn *WebsocketNetwork) setHeaders(header http.Header) {
myTelemetryGUID := wn.log.GetTelemetryHostName()
header.Set(TelemetryIDHeader, myTelemetryGUID)
header.Set(ProtocolVersionHeader, ProtocolVersion)
header.Set(AddressHeader, wn.PublicAddress())
header.Set(NodeRandomHeader, wn.RandomID)
}
// checkServerResponseVariables check that the version and random-id in the request headers matches the server ones.
// it returns true if it's a match, and false otherwise.
func (wn *WebsocketNetwork) checkServerResponseVariables(header http.Header, addr string) bool {
otherVersion := header.Get(ProtocolVersionHeader)
if otherVersion != ProtocolVersion {
wn.log.Infof("new peer %s version mismatch, mine=%s theirs=%s, headers %#v", addr, ProtocolVersion, otherVersion, header)
return false
}
otherRandom := header.Get(NodeRandomHeader)
if otherRandom == wn.RandomID || otherRandom == "" {
// This is pretty harmless and some configurations of phonebooks or DNS records make this likely. Quietly filter it out.
if otherRandom == "" {
// missing header.
wn.log.Warnf("new peer %s did not include random ID header in request. mine=%s headers %#v", addr, wn.RandomID, header)
} else {
wn.log.Debugf("new peer %s has same node random id, am I talking to myself? %s", addr, wn.RandomID)
}
return false
}
otherGenesisID := header.Get(GenesisHeader)
if wn.GenesisID != otherGenesisID {
if otherGenesisID != "" {
wn.log.Warnf("new peer %#v genesis mismatch, mine=%#v theirs=%#v, headers %#v", addr, wn.GenesisID, otherGenesisID, header)
} else {
wn.log.Warnf("new peer %#v did not include genesis header in response. mine=%#v headers %#v", addr, wn.GenesisID, header)
}
return false
}
return true
}
// getCommonHeaders retreives the common headers for both incoming and outgoing connections from the provided headers.
func getCommonHeaders(headers http.Header) (otherTelemetryGUID, otherInstanceName, otherPublicAddr string) {
otherTelemetryGUID = logging.SanitizeTelemetryString(headers.Get(TelemetryIDHeader), 1)
otherInstanceName = logging.SanitizeTelemetryString(headers.Get(InstanceNameHeader), 2)
otherPublicAddr = logging.SanitizeTelemetryString(headers.Get(AddressHeader), 1)
return
}
// checkIncomingConnectionLimits perform the connection limits counting for the incoming connections.
func (wn *WebsocketNetwork) checkIncomingConnectionLimits(response http.ResponseWriter, request *http.Request, remoteHost, otherTelemetryGUID, otherInstanceName string) int {
if wn.numIncomingPeers() >= wn.config.IncomingConnectionsLimit {
networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "incoming_connection_limit"})
wn.log.EventWithDetails(telemetryspec.Network, telemetryspec.ConnectPeerFailEvent,
telemetryspec.ConnectPeerFailEventDetails{
Address: remoteHost,
HostName: otherTelemetryGUID,
Incoming: true,
InstanceName: otherInstanceName,
Reason: "Connection Limit",
})
response.WriteHeader(http.StatusServiceUnavailable)
return http.StatusServiceUnavailable
}
totalConnections := wn.connectedForIP(remoteHost)
if totalConnections >= wn.config.MaxConnectionsPerIP {
networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "incoming_connection_per_ip_limit"})
wn.log.EventWithDetails(telemetryspec.Network, telemetryspec.ConnectPeerFailEvent,
telemetryspec.ConnectPeerFailEventDetails{
Address: remoteHost,
HostName: otherTelemetryGUID,
Incoming: true,
InstanceName: otherInstanceName,
Reason: "Remote IP Connection Limit",
})
response.WriteHeader(http.StatusServiceUnavailable)
return http.StatusServiceUnavailable
}
return http.StatusOK
}
// checkIncomingConnectionVariables checks the variables that were provided on the request, and compares them to the
// local server supported parameters. If all good, it returns http.StatusOK; otherwise, it write the error to the ResponseWriter
// and returns the http status.
func (wn *WebsocketNetwork) checkIncomingConnectionVariables(response http.ResponseWriter, request *http.Request) int {
// check to see that the genesisID in the request URI is valid and matches the supported one.
pathVars := mux.Vars(request)
otherGenesisID, hasGenesisID := pathVars["genesisID"]
if !hasGenesisID || otherGenesisID == "" {
networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "missing genesis-id"})
response.WriteHeader(http.StatusNotFound)
return http.StatusNotFound
}
if wn.GenesisID != otherGenesisID {
wn.log.Warnf("new peer %#v genesis mismatch, mine=%#v theirs=%#v, headers %#v", request.RemoteAddr, wn.GenesisID, otherGenesisID, request.Header)
networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "mismatching genesis-id"})
response.WriteHeader(http.StatusPreconditionFailed)
response.Write([]byte("mismatching genesis ID"))
return http.StatusPreconditionFailed
}
otherVersion := request.Header.Get(ProtocolVersionHeader)
if otherVersion != ProtocolVersion {
wn.log.Infof("new peer %s version mismatch, mine=%s theirs=%s, headers %#v", request.RemoteAddr, ProtocolVersion, otherVersion, request.Header)
networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "mismatching protocol version"})
response.WriteHeader(http.StatusPreconditionFailed)
message := fmt.Sprintf("Requested version %s = %s mismatches server version", ProtocolVersionHeader, otherVersion)
n, err := response.Write([]byte(message))
if err != nil {
wn.log.Warnf("ws failed to write response '%s' : n = %d err = %v", message, n, err)
}
return http.StatusPreconditionFailed
}
otherRandom := request.Header.Get(NodeRandomHeader)
if otherRandom == "" {
// This is pretty harmless and some configurations of phonebooks or DNS records make this likely. Quietly filter it out.
var message string
// missing header.
wn.log.Warnf("new peer %s did not include random ID header in request. mine=%s headers %#v", request.RemoteAddr, wn.RandomID, request.Header)
networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "missing random ID header"})
message = fmt.Sprintf("Request was missing a %s header", NodeRandomHeader)
response.WriteHeader(http.StatusPreconditionFailed)
n, err := response.Write([]byte(message))
if err != nil {
wn.log.Warnf("ws failed to write response '%s' : n = %d err = %v", message, n, err)
}
return http.StatusPreconditionFailed
} else if otherRandom == wn.RandomID {
// This is pretty harmless and some configurations of phonebooks or DNS records make this likely. Quietly filter it out.
var message string
wn.log.Debugf("new peer %s has same node random id, am I talking to myself? %s", request.RemoteAddr, wn.RandomID)
networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "matching random ID header"})
message = fmt.Sprintf("Request included matching %s=%s header", NodeRandomHeader, otherRandom)
response.WriteHeader(http.StatusLoopDetected)
n, err := response.Write([]byte(message))
if err != nil {
wn.log.Warnf("ws failed to write response '%s' : n = %d err = %v", message, n, err)
}
return http.StatusLoopDetected
}
return http.StatusOK
}
// ServerHTTP handles the gossip network functions over websockets
func (wn *WebsocketNetwork) ServeHTTP(response http.ResponseWriter, request *http.Request) {
trackedRequest := wn.requestsTracker.GetTrackedRequest(request)
if wn.checkIncomingConnectionLimits(response, request, trackedRequest.remoteHost, trackedRequest.otherTelemetryGUID, trackedRequest.otherInstanceName) != http.StatusOK {
// we've already logged and written all response(s).
return
}
if wn.checkIncomingConnectionVariables(response, request) != http.StatusOK {
// we've already logged and written all response(s).
return
}
// if UseXForwardedForAddressField is not empty, attempt to override the otherPublicAddr with the X Forwarded For origin
trackedRequest.otherPublicAddr = trackedRequest.remoteAddr
requestHeader := make(http.Header)
wn.setHeaders(requestHeader)
requestHeader.Set(GenesisHeader, wn.GenesisID)
var challenge string
if wn.prioScheme != nil {
challenge = wn.prioScheme.NewPrioChallenge()
requestHeader.Set(PriorityChallengeHeader, challenge)
}
conn, err := wn.upgrader.Upgrade(response, request, requestHeader)
if err != nil {
wn.log.Info("ws upgrade fail ", err)
networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "ws upgrade fail"})
return
}
// we want to tell the response object that the status was changed to 101 ( switching protocols ) so that it will be logged.
if wn.requestsLogger != nil {
wn.requestsLogger.SetStatusCode(response, http.StatusSwitchingProtocols)
}
peer := &wsPeer{
wsPeerCore: wsPeerCore{
net: wn,
rootURL: trackedRequest.otherPublicAddr,
originAddress: trackedRequest.remoteHost,
},
conn: conn,
outgoing: false,
InstanceName: trackedRequest.otherInstanceName,
incomingMsgFilter: wn.incomingMsgFilter,
prioChallenge: challenge,
createTime: trackedRequest.created,
}
peer.TelemetryGUID = trackedRequest.otherTelemetryGUID
peer.init(wn.config, wn.outgoingMessagesBufferSize)
wn.addPeer(peer)
localAddr, _ := wn.Address()
wn.log.With("event", "ConnectedIn").With("remote", trackedRequest.otherPublicAddr).With("local", localAddr).Infof("Accepted incoming connection from peer %s", trackedRequest.otherPublicAddr)
wn.log.EventWithDetails(telemetryspec.Network, telemetryspec.ConnectPeerEvent,
telemetryspec.PeerEventDetails{
Address: trackedRequest.remoteHost,
HostName: trackedRequest.otherTelemetryGUID,
Incoming: true,
InstanceName: trackedRequest.otherInstanceName,
})
peers.Set(float64(wn.NumPeers()), nil)
incomingPeers.Set(float64(wn.numIncomingPeers()), nil)
}
func (wn *WebsocketNetwork) messageHandlerThread() {
defer wn.wg.Done()
inactivityCheckTicker := time.NewTicker(connectionActivityMonitorInterval)
defer inactivityCheckTicker.Stop()
for {
select {
case <-wn.ctx.Done():
return
case msg := <-wn.readBuffer:
if msg.processing != nil {
// The channel send should never block, but just in case..
select {
case msg.processing <- struct{}{}:
default:
wn.log.Warnf("could not send on msg.processing")
}
}
if wn.config.EnableOutgoingNetworkMessageFiltering && len(msg.Data) >= messageFilterSize {
wn.sendFilterMessage(msg)
}
//wn.log.Debugf("msg handling %#v [%d]byte", msg.Tag, len(msg.Data))
start := time.Now()
// now, send to global handlers
outmsg := wn.handlers.Handle(msg)
handled := time.Now()
bufferNanos := start.UnixNano() - msg.Received
networkIncomingBufferMicros.AddUint64(uint64(bufferNanos/1000), nil)
handleTime := handled.Sub(start)
networkHandleMicros.AddUint64(uint64(handleTime.Nanoseconds()/1000), nil)
switch outmsg.Action {
case Disconnect:
wn.wg.Add(1)
go wn.disconnectThread(msg.Sender, disconnectBadData)
case Broadcast:
wn.Broadcast(wn.ctx, msg.Tag, msg.Data, false, msg.Sender)
default:
}
case <-inactivityCheckTicker.C:
// go over the peers and ensure we have some type of communication going on.
wn.checkPeersConnectivity()
}
}
}
// checkPeersConnectivity tests the last timestamp where each of these
// peers was communicated with, and disconnect the peer if it has been too long since
// last time.
func (wn *WebsocketNetwork) checkPeersConnectivity() {
wn.peersLock.Lock()
defer wn.peersLock.Unlock()
currentTime := time.Now()
for _, peer := range wn.peers {
lastPacketTime := peer.GetLastPacketTime()
timeSinceLastPacket := currentTime.Sub(time.Unix(0, lastPacketTime))
if timeSinceLastPacket > maxPeerInactivityDuration {
wn.wg.Add(1)
go wn.disconnectThread(peer, disconnectIdleConn)
networkIdlePeerDrops.Inc(nil)
}