-
Notifications
You must be signed in to change notification settings - Fork 1
/
node.go
344 lines (281 loc) · 12.8 KB
/
node.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
// node.go contains types, functions and methods
// for interacting with kava nodes to determine
// their application and infrastructure health
// based off various metrics such as time behind live
// and memory consumption or i/o latency
package main
import (
"context"
"fmt"
"time"
"github.com/kava-labs/doctor/clients/kava"
"github.com/kava-labs/doctor/heal"
"github.com/kava-labs/doctor/metric"
)
// NodeClientConfig wraps config
// used for creating a NodeClient
type NodeClientConfig struct {
RPCEndpoint string
DefaultMonitoringIntervalSeconds int
Autoheal bool // whether doctor should take active measures to attempt to heal the kava process (e.g. place on standby if it falls significantly behind live)
AutohealBlockchainServiceName string
AutohealSyncLatencyToleranceSeconds int
AutohealSyncToLiveToleranceSeconds int
AutohealRestartDelaySeconds int
AutohealInitialAllowedDelaySeconds int
HealthChecksTimeoutSeconds int
NoNewBlocksRestartThresholdSeconds int
DowntimeRestartThresholdSeconds int
}
// NodeClient provides methods
// for interacting with the kava node
// API and OS shell for a given node
type NodeClient struct {
*kava.Client
config NodeClientConfig
}
// NewNodeCLient creates and returns a new node client
// using the provided configuration
func NewNodeClient(config NodeClientConfig) (*NodeClient, error) {
kavaClient, err := kava.New(kava.ClientConfig{
JSONRPCURL: config.RPCEndpoint,
HTTPReadTimeoutSeconds: config.HealthChecksTimeoutSeconds,
})
if err != nil {
panic(fmt.Errorf("%w: could not initialize kava client", err))
}
return &NodeClient{
config: config,
Client: kavaClient,
}, nil
}
// WatchSyncStatus watches (until the context is cancelled)
// the sync status for the node and sends any new data to the provided channel.
func (nc *NodeClient) WatchSyncStatus(ctx context.Context, syncStatusMetrics chan<- metric.SyncStatusMetrics, uptimeMetrics chan<- metric.UptimeMetric, logMessages chan<- string) {
// create channel that will emit
// an event every DefaultMonitoringIntervalSeconds seconds
ticker := time.NewTicker(time.Duration(nc.config.DefaultMonitoringIntervalSeconds) * time.Second).C
var outOfSyncAutohealingInProgress bool
var lastRestartedByAutohealingAt *time.Time
lastNewBlockObservedAt := time.Now()
var lastSynchedBlockNumber int64
var currentDowntimeStartedAt *time.Time
earliestAllowedRestartTime := time.Now().Add(time.Duration(nc.config.AutohealInitialAllowedDelaySeconds) * time.Second)
for {
select {
case <-ctx.Done():
return
case <-ticker:
// get the current sync status of the node
// timing how long it takes for the node
// to respond to the request as well
statusCheckStartedAt := time.Now()
nodeState, err := nc.GetNodeState()
statusCheckEndedAt := time.Now()
uptimeMetric := metric.UptimeMetric{
EndpointURL: nc.config.RPCEndpoint,
SampledAt: statusCheckStartedAt,
Up: true,
}
if err != nil {
// send uptime metric to metric collector
// for aggregation and storage
uptimeMetric.Up = false
// log error, but don't block the monitoring
// routine if the logMessage channel is full
go func() {
logMessages <- fmt.Sprintf("error %s getting node status", err)
uptimeMetrics <- uptimeMetric
}()
// if this is the first time the api was unavailable
// or it went down after being restarted
// set the start of the downtime window
if currentDowntimeStartedAt == nil {
logMessages <- fmt.Sprintf("node went offline at %+v", statusCheckStartedAt)
downtimeStartedAt := statusCheckStartedAt
currentDowntimeStartedAt = &downtimeStartedAt
}
// TODO: refactor into node.AutohealOfflineNode()
if nc.config.Autoheal {
// check if the downtime deserves a restart
downtimeDuration := statusCheckStartedAt.Sub(*currentDowntimeStartedAt)
logMessages <- fmt.Sprintf("node has been down for %+v downtime threshold seconds %v, restart delay seconds %d", downtimeDuration, nc.config.DowntimeRestartThresholdSeconds, nc.config.AutohealRestartDelaySeconds)
// if the node was previously restarted
// don't restart until AutohealRestartDelaySeconds have passed
if lastRestartedByAutohealingAt != nil {
if downtimeDuration < time.Duration(time.Duration(nc.config.AutohealRestartDelaySeconds)*time.Second) {
logMessages <- fmt.Sprintf("not restarting offline node, current downtime %v last restarted %f seconds ago at %v restart delay seconds %d", downtimeDuration, time.Since(*lastRestartedByAutohealingAt).Seconds(), lastRestartedByAutohealingAt, nc.config.AutohealRestartDelaySeconds)
// keep checking the health of the endpoint
continue
}
// restart the node
err = nc.RestartBlockchainService()
if err != nil {
logMessages <- fmt.Sprintf("error %s restarting node", err)
// keep checking the health of the endpoint
continue
}
// update the last restarted at time
now := time.Now()
lastRestartedByAutohealingAt = &now
logMessages <- fmt.Sprintf("restarted node at %v", lastRestartedByAutohealingAt)
// reset downtime clock
currentDowntimeStartedAt = nil
// keep checking the health of the endpoint
continue
}
// otherwise only restart the node if it's been down long enough
if downtimeDuration > time.Duration(time.Duration(nc.config.DowntimeRestartThresholdSeconds)*time.Second) {
// this is the first time the node is being restarted
// for the current downtime window
// restart the node
err = nc.RestartBlockchainService()
if err != nil {
logMessages <- fmt.Sprintf("error %s restarting node", err)
// keep checking the health of the endpoint
continue
}
// update the last restarted at time
now := time.Now()
lastRestartedByAutohealingAt = &now
logMessages <- fmt.Sprintf("restarted node at %v", lastRestartedByAutohealingAt)
// reset downtime clock
currentDowntimeStartedAt = nil
// keep checking the health of the endpoint
continue
}
logMessages <- fmt.Sprintf("not restarting node, down for %v seconds, downtime threshold seconds %v", downtimeDuration, nc.config.DowntimeRestartThresholdSeconds)
}
// keep watching
continue
}
var secondsBehindLive int64
currentSyncTime := nodeState.SyncInfo.LatestBlockTime
currentBlockNumber := nodeState.SyncInfo.LatestBlockHeight
secondsBehindLive = int64(time.Since(currentSyncTime).Seconds())
metrics := metric.SyncStatusMetrics{
SampledAt: statusCheckStartedAt,
NodeId: nodeState.NodeInfo.Id,
SyncStatus: nodeState.SyncInfo,
SampleLatencyMilliseconds: statusCheckEndedAt.Sub(statusCheckStartedAt).Milliseconds(),
SecondsBehindLive: secondsBehindLive,
}
go func() {
logMessages <- fmt.Sprintf("node state %+v", nodeState)
syncStatusMetrics <- metrics
uptimeMetrics <- uptimeMetric
}()
// if the node has synched any new blocks since the last block
if currentBlockNumber > lastSynchedBlockNumber {
// update frozen node health indicator
lastNewBlockObservedAt = statusCheckEndedAt
logMessages <- "node has synched new blocks since last check"
} else {
logMessages <- fmt.Sprintf("node has been frozen for %f seconds since %v\n NoNewBlocksRestartThresholdSeconds %d", statusCheckEndedAt.Sub(lastNewBlockObservedAt).Seconds(), lastNewBlockObservedAt, nc.config.NoNewBlocksRestartThresholdSeconds)
}
// TODO: refactor into node.AutohealOutOfSyncNode()
if nc.config.Autoheal {
go func() {
logMessages <- fmt.Sprintf("AutoHeal: node %s is %d seconds behind live, AutohealSyncLatencyToleranceSeconds %d, ", nodeState.NodeInfo.Id, secondsBehindLive, int64(nc.config.AutohealSyncLatencyToleranceSeconds))
}()
if secondsBehindLive > int64(nc.config.AutohealSyncLatencyToleranceSeconds) {
go func() {
logMessages <- fmt.Sprintf("node %s is more than %d seconds behind live: %d, checking to see if it is already being healed", nodeState.NodeInfo.Id, nc.config.AutohealSyncLatencyToleranceSeconds, secondsBehindLive)
}()
// check to see if there is already a healer working on this issue
if outOfSyncAutohealingInProgress {
go func() {
logMessages <- fmt.Sprintf("AutoHeal: node %s is currently being autohealed", nodeState.NodeInfo.Id)
}()
goto AutohealFrozenNodeBegin
}
outOfSyncAutohealingInProgress = true
go func() {
logMessages <- fmt.Sprintf("node %s is more than %d seconds behind live: %d, attempting autohealing actions", nodeState.NodeInfo.Id, nc.config.AutohealSyncLatencyToleranceSeconds, secondsBehindLive)
}()
// node, heal thyself
go func() {
defer func() {
go func() {
logMessages <- "AutoHeal: releasing lock"
}()
outOfSyncAutohealingInProgress = false
go func() {
logMessages <- "AutoHeal: released lock"
}()
}()
heal.StandbyNodeUntilCaughtUp(logMessages, nc.Client, heal.HealerConfig{
AutohealSyncToLiveToleranceSeconds: nc.config.AutohealSyncToLiveToleranceSeconds,
})
}()
} else {
logMessages <- fmt.Sprintf("node %s is less than %d seconds behind live, doesn't need to be auto healed", nodeState.NodeInfo.Id, nc.config.AutohealSyncLatencyToleranceSeconds)
}
} else {
logMessages <- fmt.Sprintf("auto heal not enabled for node %s, skipping autoheal checks", nodeState.NodeInfo.Id)
}
AutohealFrozenNodeBegin:
// TODO: refactor into node.AutohealFrozenNode()
if nc.config.Autoheal {
// if configured, allow an initial buffer from service start to first autoheal restart
// if we are still in that initial buffer. if so, continue checking the health
if time.Now().Before(earliestAllowedRestartTime) {
logMessages <- fmt.Sprintf("not restarting frozen node, still in initial restart delay buffer: buffer %d sec, first restart allowed at %s", nc.config.AutohealInitialAllowedDelaySeconds, earliestAllowedRestartTime)
continue
}
// check if the node has been frozen long enough to deserve a restart
frozenDuration := time.Since(lastNewBlockObservedAt)
if frozenDuration > time.Duration(time.Duration(nc.config.NoNewBlocksRestartThresholdSeconds)*time.Second) {
// if the node was previously restarted
// don't restart until AutohealRestartDelaySeconds have passed
if lastRestartedByAutohealingAt != nil {
if frozenDuration < time.Duration(time.Duration(nc.config.AutohealRestartDelaySeconds)*time.Second) {
logMessages <- fmt.Sprintf("not restarting frozen node, current freezetime %v last restarted %f seconds ago at %v restart delay seconds %d", frozenDuration, time.Since(*lastRestartedByAutohealingAt).Seconds(), lastRestartedByAutohealingAt, nc.config.AutohealRestartDelaySeconds)
// keep checking the health of the endpoint
continue
}
// restart the node
err = nc.RestartBlockchainService()
if err != nil {
logMessages <- fmt.Sprintf("error %s restarting node", err)
// keep checking the health of the endpoint
continue
}
// update the last restarted at time
now := time.Now()
lastRestartedByAutohealingAt = &now
logMessages <- fmt.Sprintf("restarted node at %v", lastRestartedByAutohealingAt)
// reset frozen clock
lastNewBlockObservedAt = time.Now()
// keep checking the health of the endpoint
continue
}
logMessages <- fmt.Sprintf("autohealing frozen node, last block synched at %v,NoNewBlocksRestartThresholdSeconds %d", lastNewBlockObservedAt, nc.config.NoNewBlocksRestartThresholdSeconds)
// restart the node
err = nc.RestartBlockchainService()
if err != nil {
logMessages <- fmt.Sprintf("error %s restarting node", err)
// keep checking the health of the endpoint
continue
}
// update the last restarted at time
now := time.Now()
lastRestartedByAutohealingAt = &now
logMessages <- fmt.Sprintf("restarted node at %v", lastRestartedByAutohealingAt)
// reset frozen clock
lastNewBlockObservedAt = time.Now()
// keep checking the health of the endpoint
continue
}
logMessages <- fmt.Sprintf("not restarting node, frozen for %v seconds, frozen threshold seconds %v", frozenDuration.Seconds(), nc.config.NoNewBlocksRestartThresholdSeconds)
}
// update frozen node health indicator
lastSynchedBlockNumber = currentBlockNumber
}
}
}
// RestartBlockchainService restarts the blockchain's systemd service
// returning error (if any)
func (nc *NodeClient) RestartBlockchainService() error {
return heal.RestartSystemdService(nc.config.AutohealBlockchainServiceName)
}