-
Notifications
You must be signed in to change notification settings - Fork 0
/
peer_monitor.go
223 lines (174 loc) · 5.31 KB
/
peer_monitor.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
package peer_monitor
import (
"context"
"encoding/json"
"net/netip"
"sort"
"sync"
"github.com/warp-contracts/syncer/src/utils/arweave"
"github.com/warp-contracts/syncer/src/utils/config"
"github.com/warp-contracts/syncer/src/utils/monitoring"
"github.com/warp-contracts/syncer/src/utils/slice"
"github.com/warp-contracts/syncer/src/utils/task"
"time"
)
type PeerMonitor struct {
*task.Task
client *arweave.Client
// State
blacklist Blacklist
monitor monitoring.Monitor
}
type metric struct {
Peer string
Height int64
Blocks int64
Duration time.Duration
}
func (self *metric) String() string {
b, _ := json.Marshal(self)
return string(b)
}
func NewPeerMonitor(config *config.Config) (self *PeerMonitor) {
self = new(PeerMonitor)
self.Task = task.NewTask(config, "peer-monitor").
WithPeriodicSubtaskFunc(config.PeerMonitor.Period, self.runPeriodically).
WithWorkerPool(config.PeerMonitor.NumWorkers, config.PeerMonitor.WorkerQueueSize)
return
}
func (self *PeerMonitor) WithClient(client *arweave.Client) *PeerMonitor {
self.client = client
return self
}
func (self *PeerMonitor) WithMonitor(monitor monitoring.Monitor) *PeerMonitor {
self.monitor = monitor
return self
}
// Periodically checks Arweave network info for updated height
func (self *PeerMonitor) runPeriodically() (err error) {
height, err := self.getTrustedHeight()
if err != nil {
self.Log.WithError(err).Error("Failed to get trusted height")
return nil
}
peers, err := self.getPeers()
if err != nil {
self.Log.WithError(err).Error("Failed to get peers")
return nil
}
peers = self.sortPeersByMetrics(height, peers)
numPeers := len(peers)
if numPeers > self.Config.PeerMonitor.MaxPeers {
numPeers = self.Config.PeerMonitor.MaxPeers
}
self.client.SetPeers(peers[:numPeers])
self.monitor.GetReport().Peer.State.NumPeers.Store(uint64(numPeers))
self.monitor.GetReport().Peer.State.PeersBlacklisted.Store(uint64(self.blacklist.Size.Load()))
self.Log.WithField("numBlacklisted", self.blacklist.Size.Load()).Trace("Set new peers")
self.blacklist.RemoveOldest(self.Config.PeerMonitor.MaxPeersRemovedFromBlacklist)
return nil
}
func (self *PeerMonitor) getTrustedHeight() (out int64, err error) {
// Use a specific URL as the source of truth, to avoid race conditions with SDK
ctx := context.WithValue(self.Ctx, arweave.ContextForcePeer, self.Config.NetworkMonitor.Url)
ctx = context.WithValue(ctx, arweave.ContextDisablePeers, true)
networkInfo, err := self.client.GetNetworkInfo(ctx)
if err != nil {
return
}
out = networkInfo.Height
return
}
func (self *PeerMonitor) getPeers() (peers []string, err error) {
// Get peers available in the network
allPeers, err := self.client.GetPeerList(self.Ctx)
if err != nil {
self.Log.Error("Failed to get Arweave peer list")
self.monitor.GetReport().Peer.Errors.PeerDownloadErrors.Inc()
return
}
self.Log.WithField("numPeers", len(allPeers)).Debug("Got peers")
// Slice of checked addresses in proper format
peers = make([]string, 0, len(allPeers))
var addr netip.AddrPort
for _, peer := range allPeers {
// Validate peer address
addr, err = netip.ParseAddrPort(peer)
if err != nil || !addr.IsValid() {
self.Log.WithField("peer", peer).Error("Bad peer address")
continue
}
// Peers are in format <ip>:<port>, add http schema
peers = append(peers, "http://"+peer)
}
return
}
func (self *PeerMonitor) sortPeersByMetrics(height int64, allPeers []string) (peers []string) {
self.Log.Debug("Checking peers")
// Sync between workers
var mtx sync.Mutex
var wg sync.WaitGroup
wg.Add(len(allPeers))
// Metrics used to sort peers
metrics := make([]*metric, 0, len(allPeers))
// Perform test requests
for i, peer := range allPeers {
// Copy variables
peer := peer
i := i
self.SubmitToWorker(func() {
var (
info *arweave.NetworkInfo
duration time.Duration
err error
)
// Neglect blacklisted peers
if self.blacklist.Contains(peer) {
goto end
}
self.Log.WithField("peer", peer).WithField("idx", i).WithField("maxIdx", len(allPeers)-1).Trace("Checking peer")
info, duration, err = self.client.CheckPeerConnection(self.Ctx, peer)
if err != nil {
self.Log.WithField("peer", peer).Trace("Black list peer")
// Put the peer on the blacklist
self.blacklist.Add(peer)
// Neglect peers that returned and error
goto end
}
mtx.Lock()
metrics = append(metrics, &metric{
Duration: duration,
Height: info.Height,
Blocks: info.Blocks,
Peer: peer,
})
mtx.Unlock()
// self.Log.WithField("metric", metrics[len(metrics)-1]).Info("Metric")
end:
wg.Done()
})
}
// Wait for workers to finish
wg.Wait()
// Filter out peers that are too far out
metrics = slice.Filter(metrics, func(m *metric) bool {
// TODO: Move this constant to dedicated config
return height-m.Height < 50
})
// Sort using response times (less is better)
sort.Slice(metrics, func(i int, j int) bool {
return metrics[i].Duration < metrics[j].Duration
})
// Sort using number of not synchronized blocks (less is better)
sort.SliceStable(metrics, func(i int, j int) bool {
a := metrics[i]
b := metrics[j]
return (a.Height-a.Blocks < b.Height-b.Blocks)
})
// Get the sorted peers
peers = make([]string, len(metrics))
for i, metric := range metrics {
peers[i] = metric.Peer
}
return
}