Skip to content

Commit 5c11252

Browse files
committed
Merge branch 'random-peering' of https://github.com/Cortze/armiarma into random-peering
2 parents e2af9be + bd31415 commit 5c11252

File tree

17 files changed

+678
-36
lines changed

17 files changed

+678
-36
lines changed

src/analyzer/armiarma-analyzer.py

Lines changed: 148 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -235,20 +235,23 @@ def plotSinglePieFromArray(xarray, pdf, opts):
235235
fig, ax = plt.subplots(figsize=opts['figsize'])
236236

237237
size = opts['piesize']
238-
239-
"""
240-
cmap = plt.get_cmap(opts['piecolors'])
241-
pcolors = cmap(np.arange(1)*len(xarray))
242-
"""
243-
244-
patches1, labels1 = ax.pie(xarray, radius=1, colors=opts['piecolors'], labels=opts['labels'],
245-
wedgeprops=dict(width=size, edgecolor=opts['edgecolor']))
246238

239+
patches1, labels1, autotext = ax.pie(xarray, radius=1, colors=opts['piecolors'], labels=opts['labels'], startangle = 90,
240+
autopct='%1.1f%%', pctdistance=opts['pctdistance'], wedgeprops=dict(width=size, edgecolor=opts['edgecolor']))
241+
# autopct='%1.1f', pctdistance=opts['pctdistance'],
247242

248243
if opts['legend'] == True:
249-
plt.legend(patches1, labels1, loc=opts['lengendposition'])
244+
plt.legend(opts['labels'], bbox_to_anchor=(1, 0.75), loc=opts['lengendposition'], fontsize=opts['labelsize'],
245+
bbox_transform=plt.gcf().transFigure)
246+
plt.subplots_adjust(left=0.0, bottom=0.1, right=0.85)
250247
ax.set(aspect="equal")
251248

249+
for idx, _ in enumerate(labels1):
250+
autotext[idx].set_fontsize(opts['labelsize'])
251+
autotext[idx].set_c(opts['piecolors'][idx])
252+
if opts['autopct'] != False:
253+
labels1[idx].remove()
254+
252255
# Title
253256
plt.title(opts['title'], fontsize = opts['titlesize'])
254257
plt.tight_layout()
@@ -546,22 +549,35 @@ def main():
546549
ff = open(peerstoreFile)
547550
peerstore = json.load(ff)
548551

549-
cntU = 0
550-
cntN = 0
552+
cnt13000 = 0
553+
cnt9000 = 0
554+
cntOthers = 0
555+
noAddrs = 0
551556

552557
peerstoreLen = len(peerstore)
558+
metricsLen = len(rumorMetricsPanda)
553559
print()
554560
print('Total amount of peers on the peerstore:',peerstoreLen)
555561
for peer in peerstore:
556562
try:
557563
if '/13000/' in peerstore[peer]["addrs"][0]:
558-
cntU = cntU +1
564+
cnt13000 = cnt13000 +1
565+
elif '/9000/' in peerstore[peer]["addrs"][0]:
566+
cnt9000 = cnt9000 +1
567+
else:
568+
cntOthers = cntOthers + 1
559569
except:
560-
pass
561-
562-
print('Number of clients with the TPC port at 1300:', cntU)
563-
print()
564-
print('percentage of "Prysm" peers from the peerstore:', round((cntU*100)/peerstoreLen,2))
570+
noAddrs = noAddrs + 1
571+
572+
print('Number of clients with the TPC port at 13000:', cnt13000)
573+
print('Number of clients with the TPC port at 9000: ', cnt9000)
574+
print('Number of clients with other TCP ports: ', cntOthers)
575+
print('Number of clients without address: ', noAddrs)
576+
summ = cnt13000 + cnt9000 + cntOthers + noAddrs
577+
noPrysmPort = cnt9000 + cntOthers + noAddrs
578+
if summ != peerstoreLen:
579+
print("----> WARN: port total count doesn't match with the total peerstore")
580+
print('percentage of "Prysm" peers from the peerstore:', round((cnt13000*100)/peerstoreLen,2))
565581

566582
ff.close()
567583

@@ -582,8 +598,8 @@ def main():
582598
messageCounterArray = sorted(messageCounterArray, reverse = True)
583599
messagePercentageArray = sorted(messagePercentageArray, reverse = True)
584600

585-
print(messageCounterArray[:5])
586-
print("Total of received messages:", totalMessageCounter)
601+
#print(messageCounterArray[:5])
602+
print("\nTotal of received messages:", totalMessageCounter)
587603

588604
# Total of messages
589605
percAcumulated = 0
@@ -628,8 +644,8 @@ def main():
628644
messageCounterArray = sorted(messageCounterArray, reverse = True)
629645
messagePercentageArray = sorted(messagePercentageArray, reverse = True)
630646

631-
print(messageCounterArray[:5])
632-
print("Total of received blocks:", totalBlockCounter)
647+
#print(messageCounterArray[:5])
648+
print("\nTotal of received blocks:", totalBlockCounter)
633649

634650
percAcumulated = 0
635651
itemsCounter = 0
@@ -669,7 +685,7 @@ def main():
669685
rumorMetricsPanda.at[index,'Client'] = "Lodestar"
670686
rumorMetricsPanda.at[index,'Version'] = ua[1]
671687
except:
672-
print("*")
688+
pass
673689

674690
# End Temp
675691

@@ -700,6 +716,48 @@ def main():
700716
peerMetricsSize = getLengthOfPanda(rumorMetricsPanda)
701717

702718
print("Attempted and succeed", succeed, "| On the metrics", peerMetricsSize)
719+
720+
if succeed < peerMetricsSize:
721+
print("- Dismatch on the extra metrics and metrics -")
722+
for idx, row in rumorMetricsPanda.iterrows():
723+
index = extraPeerData.index[extraPeerData['Peer Id'] == row['Peer Id']]
724+
extraPeerData.loc[index, 'Attempted'] = True
725+
extraPeerData.loc[index, 'Succeed'] = True
726+
extraPeerData.loc[index, 'Error'] = "None"
727+
# plot the metrics gathered on the extra-metrics
728+
nonAttempted = 0
729+
succeed = 0
730+
failed = 0
731+
print("\n -- Updating extra-results -- \n")
732+
print("extra metrics len:", len(extraPeerData))
733+
for index, row in extraPeerData.iterrows():
734+
if row['Attempted'] == False:
735+
nonAttempted = nonAttempted + 1
736+
else:
737+
if row['Succeed'] == False:
738+
failed = failed + 1
739+
else:
740+
succeed = succeed + 1
741+
742+
print("Not tried from the last peerstore copy:",nonAttempted)
743+
print("Tried and succeed:", succeed)
744+
print("Tried and failed", failed)
745+
nonAttempted = nonAttempted + (peerstoreLen - (len(extraPeerData)))
746+
print("Total Not tried from the entrire peerstore", nonAttempted)
747+
748+
749+
print("Attempted and succeed", succeed, "| On the metrics", peerMetricsSize)
750+
if succeed != peerMetricsSize:
751+
print("----> WARN: Random connected peers and peers on the metrics don't match")
752+
753+
## -- website code --
754+
print("\n")
755+
print("Results from crawler run on [month] running for [crawling time].<br>Total amount of peers on the peerstore:", peerstoreLen,".<br>Number of clients with the TPC port at 13000 (Prysm?):", cnt13000,".<br>Percentage of 'Prysm' peers from the peerstore (based on the TCP port):", round((cnt13000*100)/peerstoreLen,2),"%.<br>We manage to connect with", succeed,"peers from the peerstore.<br>This would be the distribution.")
756+
print("\n")
757+
758+
759+
760+
703761
xarray = [[0, succeed], [0, failed], [0, nonAttempted], [peerstoreLen, 0]]
704762
yarray = ['Peerstore', 'Peering Results']
705763
labels = ['connected', 'failed', 'not attempted', 'peerstore']
@@ -741,7 +799,12 @@ def main():
741799
xarray, yarray = sortArrayMaxtoMin(auxxarray, auxyarray)
742800
# Get Color Grid
743801
barColor = GetColorGridFromArray(yarray)
744-
802+
803+
print()
804+
for idx,item in enumerate(xarray):
805+
print(item, ',', yarray[idx])
806+
807+
print()
745808

746809
plotHorizontalBarsFromArrays(xarray, yarray, pdf, opts={
747810
'figSize': (12,7),
@@ -812,14 +875,76 @@ def main():
812875
print("")
813876
print("-------------------------------------------------------")
814877
print('ClientVersion, NumbersPeers')
878+
# get the exact number of peers for each client into a Dict
879+
clientsCnt = {}
880+
totalPeersPerClient = 0
815881
for idx, item in enumerate(clientList):
816882
print(item, ",", clientCounter[idx])
883+
clientsCnt[item] = clientCounter[idx]
884+
totalPeersPerClient = totalPeersPerClient + clientCounter[idx]
817885
v = types[idx]
818886
for j, n in enumerate(v):
819887
print(v[j], ",", yarray[idx][j])
820888
print("-------------------------------------------------------")
821889
print("")
822890
print("")
891+
892+
if totalPeersPerClient != metricsLen:
893+
print("----> WARN: Sum of peers per client and peers on the metrics don't match")
894+
# Extrapole the number of peers from the connected metrics to the peerstore
895+
# Delete Prysm from the extrapoling
896+
del clientsCnt['Prysm']
897+
print(clientsCnt)
898+
# Get total of non prysm peers
899+
nonPrysmObserved = 0
900+
for k in clientsCnt:
901+
nonPrysmObserved = nonPrysmObserved + clientsCnt[k]
902+
# Get for each of the clients the extrapolation to the peerstore
903+
extrapolatedClientList = {}
904+
for k in clientsCnt:
905+
extrapolatedClientList[k] = round((noPrysmPort*clientsCnt[k])/nonPrysmObserved, 2)
906+
907+
print(extrapolatedClientList)
908+
909+
auxSum = 0
910+
labels = []
911+
values = []
912+
for k in extrapolatedClientList:
913+
auxSum = auxSum + extrapolatedClientList[k]
914+
labels.append(k)
915+
values.append(extrapolatedClientList[k])
916+
917+
if round(auxSum,0) != noPrysmPort:
918+
print("----> WARN: Sum of peers per client that are not Prysm and peers without port 13000 don't match", auxSum, noPrysmPort)
919+
920+
921+
labels.insert(3,'Prysm')
922+
values.insert(3, cnt13000)
923+
924+
# Plot the extrapolation
925+
plotSinglePieFromArray(values, pdf, opts={
926+
'figsize': figSize,
927+
'figtitle': 'PeerstoreClientExtrapolation.png',
928+
'pdf': pdfFile,
929+
'outputpath': outputFigsFolder,
930+
'piesize': 0.3,
931+
'autopct': '%1.0f%%', # "pcts",
932+
'pctdistance': 1.15,
933+
'edgecolor': 'w',
934+
'labels': labels,
935+
'labeldistance': 1,
936+
'piecolors': clientColors,
937+
'shadow': None,
938+
'startangle': 90,
939+
'title': "Extrapolation of Peers per Clients in the Peerstore",
940+
'titlesize': titleSize,
941+
'labelsize': labelSize-4,
942+
'legend': True,
943+
'lengendposition': None,
944+
'legendsize': labelSize,
945+
'show': False})
946+
947+
823948
# get the number of peers per country
824949
countriesList = getItemsFromColumn(rumorMetricsPanda, 'Country')
825950
auxxarray, auxyarray = getDataFromPanda(rumorMetricsPanda, None, "Country", countriesList, 'counter')

src/control/actor/gossip/topic/export_metris.go

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@ import (
44
"context"
55
"time"
66

7+
"github.com/libp2p/go-libp2p-core/host"
78
"github.com/protolambda/rumor/control/actor/base"
89
"github.com/protolambda/rumor/metrics"
10+
"github.com/protolambda/rumor/metrics/custom"
911
"github.com/protolambda/rumor/p2p/track"
1012
)
1113

@@ -19,6 +21,7 @@ type TopicExportMetricsCmd struct {
1921
PeerstorePath string `ask:"--peerstore-path" help:"The path of the file where to export the peerstore."`
2022
CsvPath string `ask:"--csv-file" help:"The path where the csv file will be exported"`
2123
ExtraMetricsPath string `ask:"--extra-metrics-path" help:"The path to the csv file where the extra metrics will be exported"`
24+
CustomMetricsPath string `ask:"--custom-metrics-path" help:"The path to the json file where the custom metrics will be exported"`
2225
}
2326

2427
func (c *TopicExportMetricsCmd) Defaul() {
@@ -33,14 +36,25 @@ func (c *TopicExportMetricsCmd) Run(ctx context.Context, args ...string) error {
3336
if c.GossipState.GsNode == nil {
3437
return NoGossipErr
3538
}
39+
// Generate the custom Metrics to export in Json at end of execution
40+
customMetrics := custom.NewCustomMetrics()
3641
c.Log.Info("Checking for existing Metrics on Project ...")
42+
// Check if Previous GossipMetrics were generated
3743
err, fileExists := c.GossipMetrics.ImportMetrics(c.FilePath)
3844
if fileExists && err != nil {
3945
c.Log.Error("Error Importing the metrics from the previous file", err)
4046
}
4147
if !fileExists {
4248
c.Log.Info("Not previous metrics found, generating new ones")
4349
}
50+
// Check if Previous ExtraMetrics were generated
51+
err, fileExists = c.GossipMetrics.ExtraMetrics.ImportMetrics(c.ExtraMetricsPath)
52+
if fileExists && err != nil {
53+
c.Log.Error("Error Importing the extra-metrics from the previous file", err)
54+
}
55+
if !fileExists {
56+
c.Log.Info("Not previous extra-metrics found, generating new ones")
57+
}
4458
stopping := false
4559
go func() {
4660
for {
@@ -69,8 +83,66 @@ func (c *TopicExportMetricsCmd) Run(ctx context.Context, args ...string) error {
6983
c.Control.RegisterStop(func(ctx context.Context) error {
7084
stopping = true
7185
c.Log.Infof("Stoped Exporting")
86+
h, _ := c.Host()
87+
// Exporting the CustomMetrics for last time (still don't know which is the best place where to put this call)
88+
err := FilCustomMetrics(c.GossipMetrics, c.Store, &customMetrics, h)
89+
if err != nil {
90+
return err
91+
}
92+
// export the CustomMetrics into a json
93+
err = customMetrics.ExportJson(c.CustomMetricsPath)
94+
if err != nil {
95+
return err
96+
}
7297
return nil
7398
})
7499

75100
return nil
76101
}
102+
103+
104+
// fulfil the info from the Custom Metrics
105+
func FilCustomMetrics(gm *metrics.GossipMetrics, ps track.ExtendedPeerstore, cm *custom.CustomMetrics, h host.Host) error{
106+
// TODO: - Generate and do the client version stuff
107+
108+
// Get total peers in peerstore
109+
peerstoreLen := custom.TotalPeers(h)
110+
// get the connection status for each of the peers in the extra-metrics
111+
succeed, failed, notattempted := gm.ExtraMetrics.GetConnectionMetrics(h)
112+
// Analyze the reported error by the connection attempts
113+
resetbypeer, timeout, dialtoself, dialbackoff, uncertain := gm.ExtraMetrics.GetErrorCounter(h)
114+
// Filter peers on peerstore by port
115+
x, y, z := custom.GetPeersWithPorts(h, ps)
116+
// Generate the MetricsDataFrame of the Current Metrics
117+
mdf := metrics.NewMetricsDataFrame(gm.GossipMetrics)
118+
lig := mdf.AnalyzeClientType("Lighthouse")
119+
tek := mdf.AnalyzeClientType("Teku")
120+
nim := mdf.AnalyzeClientType("Nimbus")
121+
pry := mdf.AnalyzeClientType("Prysm")
122+
lod := mdf.AnalyzeClientType("Lodestar")
123+
unk := mdf.AnalyzeClientType("Unknown")
124+
125+
// read client versions from Metrics
126+
cm.PeerStore.SetTotal(peerstoreLen)
127+
cm.PeerStore.SetPort13000(x)
128+
cm.PeerStore.SetPort9000(y)
129+
cm.PeerStore.SetPortDiff(z)
130+
cm.PeerStore.SetNotAttempted(notattempted)
131+
cm.PeerStore.ConnectionFailed.SetTotal(failed)
132+
cm.PeerStore.ConnectionFailed.SetResetByPeer(resetbypeer)
133+
cm.PeerStore.ConnectionFailed.SetTimeOut(timeout)
134+
cm.PeerStore.ConnectionFailed.SetDialToSelf(dialtoself)
135+
cm.PeerStore.ConnectionFailed.SetDialBackOff(dialbackoff)
136+
cm.PeerStore.ConnectionFailed.SetUncertain(uncertain)
137+
138+
// fill the CustomMetrics with the readed information
139+
cm.PeerStore.ConnectionSucceed.SetTotal(succeed)
140+
cm.PeerStore.ConnectionSucceed.Lighthouse = lig
141+
cm.PeerStore.ConnectionSucceed.Teku = tek
142+
cm.PeerStore.ConnectionSucceed.Nimbus = nim
143+
cm.PeerStore.ConnectionSucceed.Prysm = pry
144+
cm.PeerStore.ConnectionSucceed.Lodestar = lod
145+
cm.PeerStore.ConnectionSucceed.Unknown = unk
146+
147+
return nil
148+
}

src/control/actor/host/notify.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,6 @@ func (c *HostNotifyCmd) listenCloseF(net network.Network, addr ma.Multiaddr) {
4949
}
5050

5151
func (c *HostNotifyCmd) connectedF(net network.Network, conn network.Conn) {
52-
fmt.Println("Host-Notifier: Connected to new peer:", conn.RemotePeer().String())
5352
c.GossipMetrics.AddNewPeer(conn.RemotePeer())
5453
c.GossipMetrics.AddConnectionEvent(conn.RemotePeer(), "Connection")
5554

0 commit comments

Comments
 (0)