-
Notifications
You must be signed in to change notification settings - Fork 13
/
peer.go
805 lines (704 loc) · 25.6 KB
/
peer.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
package models
import (
"fmt"
"strconv"
"strings"
"time"
bc_topics "github.com/migalabs/armiarma/src/gossipsub/blockchaintopics"
"github.com/migalabs/armiarma/src/utils"
ma "github.com/multiformats/go-multiaddr"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
var (
MaxArraySize int = 10
ModuleName string = "Peer"
log = logrus.WithField(
"module", ModuleName,
)
)
// Stores all the information related to a peer
type Peer struct {
// PeerBASICS
PeerId string
UserAgent string
ClientName string
ClientOS string //TODO:
ClientVersion string
// PeerNetwork
Ip string
Country string
CountryCode string
City string
Latency float64
MAddrs []ma.Multiaddr
Protocols []string
ProtocolVersion string
// PeerMetrics
ConnectedDirection []string // The directions of each connection event.
IsConnected bool // If the peer is connected (CheckIfRealConnect).
Attempted bool // If the peer has been attempted to stablish a connection.
Succeed bool // If the connection attempt (outbound) has been successful.
Attempts uint64 // Number of attempts done.
Error []string // List of errors (also adding "None" errors), aligned with connection events.
LastErrorTimestamp time.Time // Timestamp of the last error reported for this peer.
Deprecated bool // Flag to rummarize whether the peer is still valid for statistics or not. If true, the peer is not exported CSV / metrics.
LastIdentifyTimestamp time.Time // Timestamp of the last time the peer was identified (get user agent...).
NegativeConnAttempts []time.Time // List of dates when the peer retrieved a negative connection attempt (outbound) (if there is a possitive one, clean the array).
ConnectionTimes []time.Time // List of registered connections events.
DisconnectionTimes []time.Time // List of Disconnection Events.
MetadataRequest bool // If the peer has been attempted to request its metadata.
MetadataSucceed bool // If the peer has been successfully requested its metadata.
LastExport int64 // Timestamp in seconds of the last exported time (backup for when we are loading the Peer).
// Application layer / extra attributes
Att map[string]interface{}
// Message
// Counters for the different topics
MessageMetrics map[string]MessageMetric
}
// Default constructor
func NewPeer(peerId string) Peer {
pm := Peer{
PeerId: peerId,
Error: make([]string, 0),
MAddrs: make([]ma.Multiaddr, 0),
Protocols: make([]string, 0),
ConnectedDirection: make([]string, 0),
NegativeConnAttempts: make([]time.Time, 0),
ConnectionTimes: make([]time.Time, 0),
DisconnectionTimes: make([]time.Time, 0),
Att: make(map[string]interface{}),
MessageMetrics: make(map[string]MessageMetric),
}
return pm
}
// FetchPeerInfoFromPeer:
// This method will read information from a new peer,
// and update the self (pm) peer with the new peer's attributes.
// Keep in mind that only fields which are not empty in the new peer
// will be overwriten in the old peer.
// @param newPeer: the peer from where to get new information and update
// the old one.
func (pm *Peer) FetchPeerInfoFromNewPeer(newPeer Peer) {
pm.FetchBasicHostInfoFromNewPeer(newPeer)
pm.FetchConnectionsFromNewPeer(newPeer)
pm.FetchAttFromNewPeer(newPeer)
}
// FetchBasicHostInfoFromNewPeer:
// This method will read basic host info from the new peer and import it
// into our peer (pm).
// @param newPeer: the peer where to extract new information.
func (pm *Peer) FetchBasicHostInfoFromNewPeer(newPeer Peer) {
// Somehow weird to update the peerID, since it is going to be the same one
pm.PeerId = getNonEmpty(pm.PeerId, newPeer.PeerId)
pm.MAddrs = getNonEmptyMAddrArray(pm.MAddrs, newPeer.MAddrs)
pm.ProtocolVersion = getNonEmpty(pm.ProtocolVersion, newPeer.ProtocolVersion)
if len(newPeer.Protocols) != 0 {
pm.Protocols = newPeer.Protocols
}
pm.Ip = getNonEmpty(pm.Ip, newPeer.Ip)
if pm.City == "" || newPeer.City != "" {
pm.City = newPeer.City
pm.Country = newPeer.Country
}
if newPeer.Latency > 0 {
pm.Latency = newPeer.Latency
}
// Check User Agent and derivated client type/version/OS
pm.UserAgent = getNonEmpty(pm.UserAgent, newPeer.UserAgent)
pm.ClientOS = getNonEmpty(pm.ClientOS, newPeer.ClientOS)
if newPeer.ClientName != "" || pm.ClientName == "" {
pm.ClientName = newPeer.ClientName
pm.ClientVersion = newPeer.ClientVersion
}
}
// FetchConnectionsFromNewPeer:
// This method will read connections from the new peer and import it
// into our peer (pm).
// @param newPeer: the peer where to extract new information.
func (pm *Peer) FetchConnectionsFromNewPeer(newPeer Peer) {
// only change these when old one was false, otherwise, leave as t is
if !pm.MetadataRequest {
pm.MetadataRequest = newPeer.MetadataRequest
}
if !pm.MetadataSucceed {
pm.MetadataSucceed = newPeer.MetadataSucceed
}
if newPeer.MetadataSucceed || newPeer.Deprecated {
pm.Deprecated = newPeer.Deprecated
}
pm.Attempts += newPeer.Attempts
if newPeer.Attempted {
pm.Attempted = newPeer.Attempted
// as it was attempted, check if there were negative connections
// if not, then clean our negative connections
if len(newPeer.NegativeConnAttempts) == 0 {
//there are no negative attempts here
pm.NegativeConnAttempts = make([]time.Time, 0)
} else {
// copy the negative attempts
pm.NegativeConnAttempts = append(pm.NegativeConnAttempts, newPeer.NegativeConnAttempts...)
}
}
if !pm.Succeed {
pm.Succeed = newPeer.Succeed
}
// Check that we dont fetch old peer into old Peer
// Edgy case that makes the memory increase exponentially after several hours of run
if len(newPeer.ConnectionTimes) > 1 {
log.Warnf("careful! peer with %d connections is getting fetched into peer with %d ones. This might end up in an exponential Heap-Memory increase.", len(newPeer.ConnectionTimes), len(pm.ConnectionTimes))
}
if len(newPeer.ConnectionTimes) != len(newPeer.ConnectedDirection) {
log.Warnf("Attention, fetching peer with different number of directions and connections")
log.Warnf("ConnectionTimes: %d, ConnectedDirection: %d", len(newPeer.ConnectionTimes), len(newPeer.ConnectedDirection))
}
connectedDirectionindex := 0
// Aggregate connections with directions and disconnections
for _, time := range newPeer.ConnectionTimes {
// check if the connection has an associated direction
newConnectedDirection := ""
// if we have exceeded the length of the array, default
if connectedDirectionindex >= len(newPeer.ConnectedDirection) {
// this should never happen, all connections must have a direction
newConnectedDirection = "unknown"
} else {
newConnectedDirection = newPeer.ConnectedDirection[connectedDirectionindex]
connectedDirectionindex++
}
pm.ConnectionEvent(newConnectedDirection, time)
}
if len(pm.ConnectedDirection) > MaxArraySize {
tmpConnDirection := pm.ConnectedDirection[len(pm.ConnectedDirection)-MaxArraySize-1 : len(pm.ConnectedDirection)-1]
pm.ConnectedDirection = tmpConnDirection
}
for _, time := range newPeer.DisconnectionTimes {
pm.DisconnectionEvent(time)
}
pm.Error = append(pm.Error, newPeer.Error...)
if len(pm.Error) > MaxArraySize {
tmpError := pm.Error[len(pm.Error)-MaxArraySize-1 : len(pm.Error)-1]
pm.Error = tmpError
}
if newPeer.LastErrorTimestamp.After(pm.LastErrorTimestamp) {
pm.LastErrorTimestamp = newPeer.LastErrorTimestamp
}
if newPeer.LastIdentifyTimestamp.After(pm.LastIdentifyTimestamp) {
pm.LastIdentifyTimestamp = newPeer.LastIdentifyTimestamp
}
}
// FetchAttFromNewPeer:
// This method will read the custom attributes from the new peer and import them
// into our peer (pm).
// @param newPeer: the peer where to extract new information.
func (pm *Peer) FetchAttFromNewPeer(newPeer Peer) {
for attName, attValue := range newPeer.Att {
pm.SetAtt(attName, attValue)
}
}
// SetAtt adds a new custom attribute to the att map
func (pm *Peer) SetAtt(key string, value interface{}) {
pm.Att[key] = value
}
// GetAtt reads custom attribute from the att map, returns interface and status of the read
func (pm *Peer) GetAtt(key string) (interface{}, bool) {
value, ok := pm.Att[key]
return value, ok
}
// ---- Deprecated for peer.GetAtt("enr") --- with the necessary string -> enode processing
//
/*
// GetBlockchainNode:
// Parses and returns the stored BlockchainNode. It uses the stored ENR to get the data.
// @return Node: the resulting node of parsing the ENR.
// @return any error if it was the case.
func (pm *Peer) GetBlockchainNode() (*enode.Node, error) {
if pm.BlockchainNodeENR == "" {
return nil, fmt.Errorf("unable to get ENODE for peer, no ENR was recorded")
}
pointer := enode.MustParse(pm.BlockchainNodeENR)
if pointer == nil {
return nil, fmt.Errorf("pointer to ENR was nil")
}
return pointer, nil
}
*/
// AddAddr:
// This method adds a new multiaddress in string format to the MAddrs array.
// @return Any error. Otherwise nil.
func (pm *Peer) AddMAddr(input_addr string) error {
new_ma, err := ma.NewMultiaddr(input_addr) // parse and format
if err != nil {
return err
}
pm.MAddrs = append(pm.MAddrs, new_ma)
return nil
}
// ExtractPublicMAddr:
// This method loops over all multiaddress and extract the first one that has
// a public IP.
// @return the found multiaddress, nil if error.
func (pm *Peer) ExtractPublicAddr() ma.Multiaddr {
// loop over all multiaddresses in the array
for _, temp_addr := range pm.MAddrs {
temp_extracted_ip := utils.ExtractIPFromMAddr(temp_addr)
// check if IP is public
if utils.IsIPPublic(temp_extracted_ip) {
// the IP is public
return temp_addr
}
}
return nil // ended loop without returning a public address
}
// ResetDynamicMetrics:
// It will reset the metrics by reinstancing the map.
func (pm *Peer) ResetDynamicMetrics() {
pm.MessageMetrics = make(map[string]MessageMetric)
}
// IsDeprecated:
// This method return the deprecated attirbute of the peer.
// @return true or false.
func (pm Peer) IsDeprecated() bool {
return pm.Deprecated
}
// LastNegAttempt:
// This method will calculate the last negative attempt time.
// @return the time of the last negative connection attempt with this peer and and error if applicable.
func (pm Peer) LastNegAttempt() (t time.Time, err error) {
if len(pm.NegativeConnAttempts) == 0 {
err = errors.New("no negative connections for the peer")
return
}
t = pm.NegativeConnAttempts[len(pm.NegativeConnAttempts)-1]
err = nil
return
}
// FirstNegAttempt:
// This method will calculate the last negative attempt time.
// @return the time of the first negative connection attempt with this peer and and error if applicable.
func (pm Peer) FirstNegAttempt() (t time.Time, err error) {
if len(pm.NegativeConnAttempts) == 0 {
err = errors.New("no negative connections for the peer")
return
}
t = pm.NegativeConnAttempts[0]
err = nil
return
}
// AddNegConnAtt:
// This method will register a new negative connection attempt in the peer (outbound).
// @param deprecated: in case we want to activate the deprecation flag.
// @param err: error string to add to the peer error list.
func (pm *Peer) AddNegConnAtt(deprecated bool, err string) {
t := time.Now()
// add a new time to the array of negative attempts
pm.NegativeConnAttempts = append(pm.NegativeConnAttempts, t)
pm.Deprecated = deprecated // set deprecated to the indicated by the param
pm.Attempts += 1
pm.Attempted = true
pm.Error = append(pm.Error, err)
pm.LastErrorTimestamp = t
}
// TODO: these two methods could possibly be merged with parameters
// AddPositiveConnAttempt:
// This method will register a new positive connection attempt in the peer (outbound).
func (pm *Peer) AddPositiveConnAttempt() {
// as we have a positive attempt, flush the negative attempts
pm.NegativeConnAttempts = make([]time.Time, 0)
pm.Deprecated = false // not deprecated anymore
pm.Attempted = true
pm.Attempts += 1
pm.Succeed = true // this peer counts now as succeeded
pm.Error = append(pm.Error, "None") // append the no error
}
// ConnectionEvent:
// Register when a new connection was detected and the direction.
// @param direction: whether inbound or outbound.
// @param time: when the event happenned.
func (pm *Peer) ConnectionEvent(direction string, time time.Time) {
pm.ConnectionTimes = append(pm.ConnectionTimes, time)
pm.ConnectedDirection = append(pm.ConnectedDirection, direction)
// update isconnected flag based on the last connection / disconnection
pm.IsConnected = pm.CheckIfPeerRealConnect()
}
// DisconnectionEvent:
// Register when a new disconnection was detected.
// @param time: when the event happenned.
func (pm *Peer) DisconnectionEvent(time time.Time) {
pm.DisconnectionTimes = append(pm.DisconnectionTimes, time)
// update isconnected flag based on the last connection / disconnection
pm.IsConnected = pm.CheckIfPeerRealConnect()
}
// CheckIfPeerRealConnect:
// This method will return whether the peer is currently connected or not.
// @return true if connected, false if not.
func (pm *Peer) CheckIfPeerRealConnect() bool {
if len(pm.ConnectionTimes) == 0 {
return false
}
lastConn := pm.ConnectionTimes[len(pm.ConnectionTimes)-1]
if len(pm.DisconnectionTimes) == 0 {
return true
}
lastDisconn := pm.DisconnectionTimes[len(pm.DisconnectionTimes)-1]
// if the last disconnection is before the last connection,
// then the connection is not closed, therefore still connected
return lastDisconn.Before(lastConn)
}
// GetLastActivityTime:
// Calculates the last activity recorded for the peer.
// @return last activity recorded for the peer.
func (pm Peer) GetLastActivityTime() time.Time {
// check len before
last_negative_activity := time.Time{}
last_connection_activity := time.Time{}
last_disconnection_activity := time.Time{}
if len(pm.NegativeConnAttempts) > 0 {
last_negative_activity = pm.NegativeConnAttempts[len(pm.NegativeConnAttempts)-1]
}
if len(pm.ConnectionTimes) > 0 {
last_connection_activity = pm.ConnectionTimes[len(pm.ConnectionTimes)-1]
}
if len(pm.DisconnectionTimes) > 0 {
last_disconnection_activity = pm.DisconnectionTimes[len(pm.DisconnectionTimes)-1]
}
return utils.ReturnGreatestTime([]time.Time{last_negative_activity,
last_connection_activity, last_disconnection_activity})
}
// GetLastErrors:
// Returns the error in last position. The array also contains the same error if it was repeated consecutively.
// @return and array with the same error.
func (pm *Peer) GetLastErrors() []string {
errorList := make([]string, 0)
lastError := ""
if len(pm.Error) > 0 { // get the last error
lastError = pm.Error[len(pm.Error)-1]
}
for i := range pm.Error {
tmpError := pm.Error[len(pm.Error)-i-1] // range backwards
if tmpError == lastError { // if the error was the same as the lastone, add it to the list
errorList = append(errorList, tmpError)
} else { // once we find a different error, then it is not consecutive anymore: break
break
}
}
return errorList
}
// GetConnectedTime:
// This method will calculate the total connected time
// based on con/disc timestamps. This means the total time that
// the peer has been connected.
// Shifted some calculus to nanoseconds. Millisecons were
// leaving fields empty when exporting (less that 3 decimals).
// @return the resulting time in float64 format.
func (pm *Peer) GetConnectedTime() float64 {
var totalConnectedTime int64
for _, conTime := range pm.ConnectionTimes {
for _, discTime := range pm.DisconnectionTimes {
singleConnectionTime := discTime.Sub(conTime)
if singleConnectionTime >= 0 {
totalConnectedTime += int64(singleConnectionTime * time.Nanosecond)
break
} else {
}
}
}
return float64(totalConnectedTime) / 60000000000
}
// MetadataEvent:
// Add a Metadata Event to the given peer (successful or not).
// @param success: whether successful (to identify the peer) or not.
func (pm *Peer) MetadataEvent(success bool) {
pm.MetadataRequest = true
pm.MetadataSucceed = success
}
// Information regarding the messages received on a given topic
type MessageMetric struct {
Count uint64
FirstMessageTime time.Time
LastMessageTime time.Time
}
// MessageEvent:
// Add one to the message count for the given topic.
// Also update the LastMessageTime.
// @param topicName: the topic to add a message on.
// @param time: when it was received.
func (pm *Peer) MessageEvent(topicName string, time time.Time) {
m, ok := pm.MessageMetrics[topicName]
if !ok {
m = MessageMetric{
FirstMessageTime: time,
}
}
m.LastMessageTime = time
m.Count++
pm.MessageMetrics[topicName] = m
}
// GetNumOfMsgFromTopic:
// Get the number of messages that we got for a given topic. Note that
// the topic name is the shortened name i.e. BeaconBlock
// @param shortTopic: the topic to get count from.
// @return a uint64 with the total count.
func (pm *Peer) GetNumOfMsgFromTopic(shortTopic string) uint64 {
msgMetric, ok := pm.MessageMetrics[bc_topics.GenerateEth2Topics(bc_topics.MainnetKey, shortTopic)]
if ok {
return msgMetric.Count
}
return uint64(0)
}
// GetAllMessagesCount:
// Get total of messages received from that peer.
// @return a unit64 with the count.
func (pm *Peer) GetAllMessagesCount() uint64 {
totalMessages := uint64(0)
for _, messageMetric := range pm.MessageMetrics {
totalMessages += messageMetric.Count
}
return totalMessages
}
// getNonEmpty:
// This method will compare two strings and return one of them.
// @param old: the old string.
// @param new: the new string.
// @return the new string in case not empty, the old one in any other case.
func getNonEmpty(old string, new string) string {
if new != "" {
return new
}
return old
}
// getNonEmptyMAddrArray:
// This method will compare two multiaddresses arrays and return one of them.
// @param old: the old (already in db) multiaddress array.
// @param new: the new (just found) multiadddress array.
// @return the new ma array in case not empty, the old one in any other case.
func getNonEmptyMAddrArray(old []ma.Multiaddr, new []ma.Multiaddr) []ma.Multiaddr {
if len(new) != 0 {
return new
}
return old
}
// ToCsvLine:
// This method will export all peer attributes into a single string
// in CSV format.
// @return the resulting string.
func (pm *Peer) ToCsvLine() string {
// register if the peer was conected
connStablished := "false"
if len(pm.ConnectionTimes) > 0 {
connStablished = "true"
}
// get the multiaddress of the peers
uniqueAddr := ""
if len(pm.MAddrs) != 0 {
mAddrss := pm.ExtractPublicAddr()
if mAddrss != nil {
uniqueAddr = mAddrss.String()
} else {
uniqueAddr = pm.MAddrs[0].String()
}
}
/* -- Deprecated --
node, err := pm.GetBlockchainNode()
forkDigest := ""
if err != nil {
log.Errorf("Could not parse ENR to CSV")
} else {
eth2Dat, _, err := all_utils.ParseNodeEth2Data(*node)
if err == nil {
forkDigest = eth2Dat.ForkDigest.String()
}
}
*/
lastConnectionTime := ""
if len(pm.ConnectionTimes) > 0 {
lastConnectionTime = pm.ConnectionTimes[len(pm.ConnectionTimes)-1].String()
}
csvRow := pm.PeerId + "," +
pm.UserAgent + "," +
pm.ClientName + "," +
pm.ClientVersion + "," +
uniqueAddr + "," +
pm.Ip + "," +
pm.Country + "," +
pm.City + "," +
strconv.FormatBool(pm.MetadataRequest) + "," +
strconv.FormatBool(pm.MetadataSucceed) + "," +
strconv.FormatBool(pm.Attempted) + "," +
strconv.FormatBool(pm.Succeed) + "," +
strconv.FormatBool(pm.Deprecated) + "," +
connStablished + "," +
strconv.FormatBool(pm.IsConnected) + "," +
strconv.FormatUint(pm.Attempts, 10) + "," +
strings.Join(pm.Error, "|") + "," +
pm.LastErrorTimestamp.String() + "," +
pm.LastIdentifyTimestamp.String() + "," +
fmt.Sprintf("%.6f", pm.Latency) + "," +
fmt.Sprintf("%d", len(pm.ConnectionTimes)) + "," +
fmt.Sprintf("%d", len(pm.DisconnectionTimes)) + "," +
lastConnectionTime + "," +
strings.Join(pm.ConnectedDirection, "|") + "," +
fmt.Sprintf("%.6f", pm.GetConnectedTime()) + "\n"
return csvRow
}
// IsEmpty:
// Check if the Peer struct is Empty or not
// @return boolean
func (pm *Peer) IsEmpty() bool {
return pm.PeerId == ""
}
// LogPeer:
// Log peer information
func (pm *Peer) LogPeer() {
log.WithFields(logrus.Fields{
"PeerId": pm.PeerId,
"UserAgent": pm.UserAgent,
"Addrs": pm.MAddrs,
"Ip": pm.Ip,
"Country": pm.Country,
"City": pm.City,
"Latency": pm.Latency,
}).Info("Peer Info")
}
// ----- Deprecated Since the integration of PSQL as DB ----
//
/*
// PeerUnMarshal:
// This method will create a Peer object reading a map of (string -> interface).
// @return the resulting Peer.
func PeerUnMarshal(m map[string]interface{}) (p Peer, finErr error) {
// TEMP FIX - Check if the loaded interfaces from the peer-fields are not nil
// if any of the interfaces is nil, there was a problem Unmarshaling the peer
defer func() {
if err := recover(); err != nil {
// If the PeerId is empty, there was a promblem unmarshalling the peer
// return an error to avoid the raw panic and handle it from avobe
log.Debug("panic error detected unmarshalling peer from Json")
}
}()
// for some fields we need to perform a check and parsing
m_addrs := make([]ma.Multiaddr, 0) // where to store the unmarshalled
err := errors.New("")
if m["MAddrs"] != nil {
m_addrs, err = utils.ParseInterfaceAddrArray(m["MAddrs"].([]interface{}))
if err != nil {
log.Errorf(err.Error())
}
}
negConns := make([]time.Time, 0)
if m["NegativeConnAttempts"] != nil {
negConns, _ = utils.ParseInterfaceTimeArray(m["NegativeConnAttempts"].([]interface{}))
}
connTimes := make([]time.Time, 0)
if m["ConnectionTimes"] != nil {
connTimes, _ = utils.ParseInterfaceTimeArray(m["ConnectionTimes"].([]interface{}))
}
disconnTimes := make([]time.Time, 0)
if m["DisconnectionTimes"] != nil {
disconnTimes, _ = utils.ParseInterfaceTimeArray(m["DisconnectionTimes"].([]interface{}))
}
protocolList := make([]string, 0)
if m["Protocols"] != nil {
protocolList = utils.ParseInterfaceStringArray(m["Protocols"].([]interface{}))
}
directionList := make([]string, 0)
if m["ConnectedDirection"] != nil {
directionList = utils.ParseInterfaceStringArray(m["ConnectedDirection"].([]interface{}))
}
errorList := make([]string, 0)
if m["Error"] != nil {
errorList = utils.ParseInterfaceStringArray(m["Error"].([]interface{}))
}
protocolVersionNew := ""
if m["ProtocolVersion"] != nil {
protocolVersionNew = m["ProtocolVersion"].(string)
}
msgMetrics := make(map[string]MessageMetric)
if m["MessageMetrics"] != nil {
msgMetrics, err = ParseInterfaceMapMessageMetrics(m["MessageMetrics"].(map[string]interface{}))
if err != nil {
log.Warnf("unable to cast full gossip msg metrics while unmarshaling. %s", err.Error())
}
}
beaconStatus := BeaconStatusStamped{}
if m["BeaconStatus"] != nil {
beaconStatus, err = ParseBeaconStatusFromInterface(m["BeaconStatus"])
if err != nil {
log.Warnf("unable to cast beaconStatus while unmarshaling. %s", err.Error())
}
}
lastError, err := time.Parse(time.RFC3339, m["LastErrorTimestamp"].(string))
if err != nil {
lastError = time.Time{}
}
lastIdentify, err := time.Parse(time.RFC3339, m["LastIdentifyTimestamp"].(string))
if err != nil {
lastIdentify = time.Time{}
}
// TODO: use constants for names
p = Peer{
PeerId: m["PeerId"].(string),
Pubkey: m["Pubkey"].(string),
NodeId: m["NodeId"].(string),
UserAgent: m["UserAgent"].(string),
ClientName: m["ClientName"].(string),
ClientOS: m["ClientOS"].(string),
ClientVersion: m["ClientVersion"].(string),
BlockchainNodeENR: m["BlockchainNodeENR"].(string),
Ip: m["Ip"].(string),
Country: m["Country"].(string),
CountryCode: m["CountryCode"].(string),
City: m["City"].(string),
Latency: m["Latency"].(float64),
MAddrs: m_addrs, // correct
Protocols: protocolList,
ProtocolVersion: protocolVersionNew,
ConnectedDirection: directionList,
IsConnected: m["IsConnected"].(bool),
Attempted: m["Attempted"].(bool),
Succeed: m["Succeed"].(bool),
Attempts: uint64(m["Attempts"].(float64)),
Error: errorList,
LastErrorTimestamp: lastError,
LastIdentifyTimestamp: lastIdentify,
Deprecated: m["Deprecated"].(bool),
NegativeConnAttempts: negConns,
ConnectionTimes: connTimes,
DisconnectionTimes: disconnTimes,
MetadataRequest: m["MetadataRequest"].(bool),
MetadataSucceed: m["MetadataSucceed"].(bool),
LastExport: int64(m["LastExport"].(float64)),
MessageMetrics: msgMetrics,
BeaconStatus: beaconStatus,
// BeaconMetadata: m["BeaconMetadata"].(BeaconMetadataStamped),
}
return p, nil
}
*/
// ----- Deprecated Since the integration of PSQL as DB ----
//
// ParseInterfaceMapMessageMetrics:
// Parse the inputMap into the MessageMetric format
// @param inputMap: a map of string interface
// @return a map of string MessageMetric
func ParseInterfaceMapMessageMetrics(inputMap map[string]interface{}) (map[string]MessageMetric, error) {
result := make(map[string]MessageMetric)
// we will range over a slice of interfaces
for k, v := range inputMap {
vaux := v.(map[string]interface{})
ft, err := time.Parse(time.RFC3339, vaux["FirstMessageTime"].(string))
if err != nil {
return result, err
}
lt, err := time.Parse(time.RFC3339, vaux["LastMessageTime"].(string))
if err != nil {
return result, err
}
mm := MessageMetric{
Count: uint64(vaux["Count"].(float64)),
FirstMessageTime: ft,
LastMessageTime: lt,
}
result[k] = mm
}
return result, nil
}