-
Notifications
You must be signed in to change notification settings - Fork 5
/
metrics_one.go
598 lines (532 loc) · 19.1 KB
/
metrics_one.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
package plugin
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"time"
"github.com/LNOpenMetrics/go-lnmetrics.reporter/pkg/graphql"
"github.com/LNOpenMetrics/lnmetrics.utils/db/leveldb"
"github.com/LNOpenMetrics/lnmetrics.utils/log"
sysinfo "github.com/elastic/go-sysinfo/types"
"github.com/vincenzopalazzo/glightning/glightning"
)
// Information about the Payment forward by the node
type PaymentInfo struct {
// the payment is received by the channel or is sent to the channel
Direction string `json:"direction"`
// the status of the channels is completed, failed or pending
Status string `json:"status"`
// The motivation for the failure
FailureReason string `json:"failure_reason,omitempty"`
// The code of the failure
FailureCode int `json:"failure_code,omitempty"`
}
// Only a wrapper to pass collected information about the channel
// not used inside the metrics.
type ChannelInfo struct {
NodeId string
Alias string
Color string
Direction string
Forwards []*PaymentInfo
}
type ChannelSummary struct {
NodeId string `json:"node_id"`
Alias string `json:"alias"`
Color string `json:"color"`
ChannelId string `json:"channel_id"`
State string `json:"state"`
}
type ChannelsSummary struct {
TotChannels uint64 `json:"tot_channels"`
Summary []*ChannelSummary `json:"summary"`
}
// Wrap all useful information about the own node
type status struct {
//node_id string `json:node_id`
Event string `json:"event"`
// how many channels the node have
Channels *ChannelsSummary `json:"channels"`
// how many payments it forwords
Forwards *PaymentsSummary `json:"forwards"`
// unix time where the check is made.
Timestamp int64 `json:"timestamp"`
}
type channelStatus struct {
Timestamp int64 `json:"timestamp"`
// Status of the channel
Status string `json:"status"`
}
// Wrap all the information about the node that the own node
// has some channel open.
type statusChannel struct {
// short channel id
ChannelId string `json:"channel_id"`
// node id
NodeId string `json:"node_id"`
// label of the node
NodeAlias string `json:"node_alias"`
// Color of the node
Color string `json:"color"`
// the capacity of the channel
Capacity uint64 `json:"capacity"`
// how payment the channel forwords
Forwards []*PaymentInfo `json:"forwards"`
// The node answer from the ping operation
UpTimes []*channelStatus `json:"up_times"`
// the node is ready to receive payment to share?
Online bool `json:"online"`
// last message (channel_update) received from the gossip
LastUpdate uint `json:"last_update"`
// the channel is public?
Public bool `json:"public"`
// information about the direction of the channel: out, in, mutual.
Direction string `json:"direction"`
}
type osInfo struct {
// Operating system name
OS string `json:"os"`
// Version of the Operating System
Version string `json:"version"`
// architecture of the system where the node is running
Architecture string `json:"architecture"`
}
type PaymentsSummary struct {
Completed uint64 `json:"completed"`
Failed uint64 `json:"failed"`
}
// Contains the info about the ln node.
type NodeInfo struct {
Implementation string `json:"implementation"`
Version string `json:"version"`
}
// Main data structure that it is filled by the collection data phase.
type MetricOne struct {
// Internal id to identify the metric
id int `json:"-"`
// Version of metrics format, it is used to migrate the
// JSON payload from previous version of plugin.
Version int `json:"version"`
// Name of the metrics
Name string `json:"metric_name"`
// Public Key of the Node
NodeId string `json:"node_id"`
// Node Alias on the network
NodeAlias string `json:"node_alias"`
// Color of the node
Color string `json:"color"`
// Network where the node it is running
Network string `json:"network"`
// OS host information
OSInfo *osInfo `json:"os_info"`
// Node information, like version/implementation
NodeInfo *NodeInfo `json:"node_info"`
// timezone where the node is located
Timezone string `json:"timezone"`
// array of the up_time
UpTime []*status `json:"up_time"`
// map of informaton of channel information
// TODO: managing the dualfound channels
ChannelsInfo map[string]*statusChannel `json:"-"`
}
func (m MetricOne) MarshalJSON() ([]byte, error) {
// Declare a new type using the definition of MetricOne,
// the result of this is that M will have the same structure
// as MetricOne but none of its methods (this avoids recursive
// calls to MarshalJSON).
//
// Also because M and MetricOne have the same structure you can
// easily convert between those two. e.g. M(MetricOne{}) and
// MetricOne(M{}) are valid expressions.
type M MetricOne
// Declare a new type that has a field of the "desired" type and
// also **embeds** the M type. Embedding promotes M's fields to T
// and encoding/json will marshal those fields unnested/flattened,
// i.e. at the same level as the channels_info field.
type T struct {
M
ChannelsInfo []*statusChannel `json:"channels_info"`
}
// move map elements to slice
channels := make([]*statusChannel, 0, len(m.ChannelsInfo))
for _, c := range m.ChannelsInfo {
channels = append(channels, c)
}
// Pass in an instance of the new type T to json.Marshal.
// For the embedded M field use a converted instance of the receiver.
// For the ChannelsInfo field use the channels slice.
return json.Marshal(T{
M: M(m),
ChannelsInfo: channels,
})
}
// Same as MarshalJSON but in reverse.
func (instance *MetricOne) UnmarshalJSON(data []byte) error {
var jsonMap map[string]interface{}
if err := json.Unmarshal(data, &jsonMap); err != nil {
return err
}
if err := instance.Migrate(jsonMap); err != nil {
return err
}
data, err := json.Marshal(jsonMap)
if err != nil {
return err
}
type M MetricOne
type T struct {
*M
ChannelsInfo []*statusChannel `json:"channels_info"`
}
t := T{M: (*M)(instance)}
if err := json.Unmarshal(data, &t); err != nil {
return err
}
instance.ChannelsInfo = make(map[string]*statusChannel, len(t.ChannelsInfo))
for _, c := range t.ChannelsInfo {
instance.ChannelsInfo[c.ChannelId] = c
}
return nil
}
func init() {
// TODO: Fill this map on some common package.
MetricsSupported = make(map[int]string)
MetricsSupported[1] = "metric_one"
ChannelDirections = make(map[int]string)
ChannelDirections[0] = "OUTCOMING"
ChannelDirections[1] = "INCOOMING"
ChannelDirections[2] = "MUTUAL"
}
// This method is required by the
func NewMetricOne(nodeId string, sysInfo sysinfo.HostInfo) *MetricOne {
return &MetricOne{id: 1, Version: 1,
Name: MetricsSupported[1], NodeId: nodeId,
NodeAlias: "unknown",
Network: "unknown",
OSInfo: &osInfo{OS: sysInfo.OS.Name,
Version: sysInfo.OS.Version,
Architecture: sysInfo.Architecture},
NodeInfo: &NodeInfo{
Implementation: "unknown",
Version: "unknown",
},
Timezone: sysInfo.Timezone, UpTime: make([]*status, 0),
ChannelsInfo: make(map[string]*statusChannel), Color: ""}
}
// Migrate from a payload format to another, with the help of the version number.
// Note that it is required implementing a required strategy only if the some
// properties will change during the time, if somethings it is only add, we
// don't have anythings to migrate.
func (instance *MetricOne) Migrate(payload map[string]interface{}) error {
// in the test for the moment the db it is not ready
if db.GetInstance().Ready() {
metric, err := db.GetInstance().GetValue("")
if err == nil {
var newPayload map[string]interface{}
log.GetInstance().Info("Migrate the new payload stored with the empty key")
if err := json.Unmarshal([]byte(metric), &newPayload); err != nil {
log.GetInstance().Error(fmt.Sprintf("Error %s: ", err))
return err
}
if err := db.GetInstance().DeleteValue(""); err != nil {
log.GetInstance().Error(fmt.Sprintf("Error %s", err))
return err
}
for key, val := range newPayload {
payload[key] = val
}
}
}
version, found := payload["version"]
if !found || int(version.(float64)) < 1 {
log.GetInstance().Info("Migrate channels_info from version 0 to version 1")
channelsInfoMap, found := payload["channels_info"]
if !found {
log.GetInstance().Error("Error: channels_info is not in the payload for migration")
return errors.New("Error: channels_info is not in the payload for migration")
}
if reflect.ValueOf(channelsInfoMap).Kind() == reflect.Map {
channelsInfoList := make([]interface{}, 0)
for _, value := range channelsInfoMap.(map[string]interface{}) {
channelsInfoList = append(channelsInfoList, value)
}
payload["channels_info"] = channelsInfoList
payload["version"] = 1
}
}
payload["version"] = 1
return nil
}
// Generic Plugin callback that it is ran each time that the plugin need to recording a new event.
func (instance *MetricOne) onEvent(nameEvent string, lightning *glightning.Lightning) (*status, error) {
listFunds, err := lightning.ListFunds()
if err != nil {
log.GetInstance().Error(fmt.Sprintf("Error: %s", err))
return nil, err
}
if err := instance.collectInfoChannels(lightning, listFunds.Channels); err != nil {
log.GetInstance().Error(fmt.Sprintf("Error: %s", err))
// We admit this error here, we print only some log information.
}
listForwards, err := lightning.ListForwards()
if err != nil {
log.GetInstance().Error(fmt.Sprintf("Error: %s", err))
return nil, err
}
statusPayments, err := instance.makePaymentsSummary(lightning, listForwards)
if err != nil {
log.GetInstance().Error(fmt.Sprintf("Error: %s", err))
return nil, err
}
channelsSummary, err := instance.makeChannelsSummary(lightning, listFunds.Channels)
if err != nil {
log.GetInstance().Error(fmt.Sprintf("Error: %s", err))
// We admit this error here, we print only some log information.
// In the call that cause this error we make a call to getListNodes, but
// the node with that we have the channels with can be offiline for a while
// and this mean that can be out of the gossip map.
}
status := &status{Event: nameEvent,
Timestamp: time.Now().Unix(),
Channels: channelsSummary,
Forwards: statusPayments}
return status, nil
}
// One time callback called from the lightning implementation
func (instance *MetricOne) OnInit(lightning *glightning.Lightning) error {
getInfo, err := lightning.GetInfo()
if err != nil {
log.GetInstance().Error(fmt.Sprintf("Error during the OnInit method; %s", err))
return err
}
instance.NodeId = getInfo.Id
instance.Color = getInfo.Color
instance.NodeAlias = getInfo.Alias
instance.Network = getInfo.Network
instance.NodeInfo = &NodeInfo{
Implementation: "c-lightning", // It is easy, it is coupled with c-lightning plugin now
Version: getInfo.Version,
}
status, err := instance.onEvent("on_start", lightning)
if err != nil {
return err
}
instance.UpTime = append(instance.UpTime, status)
return instance.MakePersistent()
}
func (instance *MetricOne) Update(lightning *glightning.Lightning) error {
status, err := instance.onEvent("on_update", lightning)
if err != nil {
return err
}
instance.UpTime = append(instance.UpTime, status)
return instance.MakePersistent()
}
func (metric *MetricOne) UpdateWithMsg(message *Msg,
lightning *glightning.Lightning) error {
return nil
}
func (instance *MetricOne) MakePersistent() error {
json, err := instance.ToJSON()
if err != nil {
log.GetInstance().Error(fmt.Sprintf("JSON error %s", err))
return err
}
return db.GetInstance().PutValue(instance.Name, json)
}
// here the message is not useful, but we keep it only for future evolution
// or we will remove it from here.
func (instance *MetricOne) OnClose(msg *Msg, lightning *glightning.Lightning) error {
log.GetInstance().Debug("On close event on metrics called")
lastValue := &ChannelsSummary{TotChannels: 0, Summary: make([]*ChannelSummary, 0)}
forwards := &PaymentsSummary{0, 0}
if len(instance.UpTime) > 0 {
lastValue = instance.UpTime[len(instance.UpTime)-1].Channels
forwards = instance.UpTime[len(instance.UpTime)-1].Forwards
}
instance.UpTime = append(instance.UpTime,
&status{Event: "on_close",
Timestamp: time.Now().Unix(),
Channels: lastValue, Forwards: forwards})
return instance.MakePersistent()
}
func (instance *MetricOne) ToJSON() (string, error) {
json, err := json.Marshal(&instance)
if err != nil {
log.GetInstance().Error(err)
return "", err
}
return string(json), nil
}
func (instance *MetricOne) Upload(client *graphql.Client) error {
payload, err := instance.ToJSON()
if err != nil {
return err
}
if err := client.UploadMetrics(instance.NodeId, &payload); err != nil {
log.GetInstance().Error(fmt.Sprintf("Error %s: ", err))
return err
}
// Refactored this method in a utils functions
t := time.Now()
log.GetInstance().Info(fmt.Sprintf("Metric One Upload at %s", t.Format(time.RFC850)))
return nil
}
// Make a summary of all the channels information that the node have a channels with.
func (instance *MetricOne) makeChannelsSummary(lightning *glightning.Lightning, channels []*glightning.FundingChannel) (*ChannelsSummary, error) {
channelsSummary := &ChannelsSummary{TotChannels: 0, Summary: make([]*ChannelSummary, 0)}
if len(channels) > 0 {
summary := make([]*ChannelSummary, 0)
for _, channel := range channels {
if channel.State == "ONCHAIN" {
// When the channel is on chain, it is not longer a channel,
// it stay in the listfunds for 100 block (bitcoin time) after the closing commitment
log.GetInstance().Debug(fmt.Sprintf("The channel with ID %s has ON_CHAIN status", channel.Id))
continue
}
channelSummary := &ChannelSummary{NodeId: channel.Id, ChannelId: channel.ShortChannelId, State: channel.State}
// FIXME: With too many channels this can require to many node request!
// this can avoid to get all node node known, but this also can have a very big response.
node, err := lightning.GetNode(channel.Id)
if err != nil {
log.GetInstance().Error(fmt.Sprintf("Error in command listNodes in makeChannelsSummary: %s", err))
// We admit this error, a node can be forgotten by the gossip if it is offline for long time.
continue
}
channelsSummary.TotChannels++
channelSummary.Alias = node.Alias
channelSummary.Color = node.Color
summary = append(summary, channelSummary)
}
channelsSummary.Summary = summary
}
return channelsSummary, nil
}
func (instance *MetricOne) makePaymentsSummary(lightning *glightning.Lightning, forwards []glightning.Forwarding) (*PaymentsSummary, error) {
statusPayments := PaymentsSummary{Completed: 0, Failed: 0}
for _, forward := range forwards {
switch forward.Status {
case "settled":
statusPayments.Completed++
case "failed", "local_failed":
statusPayments.Failed++
default:
return nil, fmt.Errorf("Status %s unexpected", forward.Status)
}
}
return &statusPayments, nil
}
// private method of the module
func (instance *MetricOne) collectInfoChannels(lightning *glightning.Lightning, channels []*glightning.FundingChannel) error {
cache := make(map[string]bool)
for _, channel := range channels {
if err := instance.collectInfoChannel(lightning, channel); err != nil {
// void returning error here? We can continue to make the analysis over the channels
log.GetInstance().Error(fmt.Sprintf("Error: %s", err))
return err
}
cache[channel.ShortChannelId] = true
}
// make intersection of the channels in the cache and a
// channels in the metrics plugin
// this is useful to remove the metrics over closed channels
// in the metrics one we are not interested to have a story of
// of the old channels (for the moments).
for key := range instance.ChannelsInfo {
_, found := cache[key]
if !found {
delete(instance.ChannelsInfo, key)
}
}
return nil
}
func (instance *MetricOne) collectInfoChannel(lightning *glightning.Lightning,
channel *glightning.FundingChannel) error {
shortChannelId := channel.ShortChannelId
infoChannel, found := instance.ChannelsInfo[shortChannelId]
var timestamp int64 = 0
// avoid to store the wrong data related to the gossip delay.
if instance.pingNode(lightning, channel.Id) {
timestamp = time.Now().Unix()
}
info, err := instance.getChannelInfo(lightning, channel, infoChannel)
if err != nil {
log.GetInstance().Error(fmt.Sprintf("Error during get the information about the channel: %s", err))
return err
}
// A new channels found
channelStat := channelStatus{timestamp, channel.State}
if !found {
upTimes := make([]*channelStatus, 1)
upTimes[0] = &channelStat
// TODO: Could be good to have a information about the direction of the channel
newInfoChannel := statusChannel{ChannelId: shortChannelId, NodeId: info.NodeId, NodeAlias: info.Alias, Color: info.Color,
Capacity: channel.ChannelSatoshi, Forwards: info.Forwards,
UpTimes: upTimes, Online: channel.Connected}
instance.ChannelsInfo[shortChannelId] = &newInfoChannel
} else {
infoChannel.Capacity = channel.ChannelSatoshi
infoChannel.UpTimes = append(infoChannel.UpTimes, &channelStat)
infoChannel.Color = info.Color
infoChannel.Online = channel.Connected
}
return nil
}
func (instance *MetricOne) pingNode(lightning *glightning.Lightning, nodeId string) bool {
if _, err := lightning.Ping(nodeId); err != nil {
log.GetInstance().Error(fmt.Sprintf("Error during pinging node: %s", err))
return false
}
return true
}
func (instance *MetricOne) getChannelInfo(lightning *glightning.Lightning,
channel *glightning.FundingChannel, prevInstance *statusChannel) (*ChannelInfo, error) {
nodeInfo, err := lightning.GetNode(channel.Id)
// Init the default data here
channelInfo := ChannelInfo{NodeId: channel.Id, Alias: "unknown",
Color: "unknown", Direction: "unknown",
Forwards: make([]*PaymentInfo, 0)}
if err != nil {
log.GetInstance().Error(fmt.Sprintf("Error during the call listNodes: %s", err))
if prevInstance != nil {
channelInfo.Alias = prevInstance.NodeAlias
channelInfo.Color = prevInstance.Color
}
// We avoid to return the error because it is correct that the node
// it is not up and running, this means that it is fine admit an
// error here.
return &channelInfo, nil
}
channelInfo.Alias = nodeInfo.Alias
channelInfo.Color = nodeInfo.Color
listForwards, err := lightning.ListForwards()
if err != nil {
log.GetInstance().Error(fmt.Sprintf("Error during the listForwards call: %s", err))
return nil, err
}
for _, forward := range listForwards {
if channel.ShortChannelId == forward.InChannel {
channelInfo.Forwards = append(channelInfo.Forwards, &PaymentInfo{Direction: ChannelDirections[1], Status: forward.Status})
} else if channel.ShortChannelId == forward.OutChannel {
channelInfo.Forwards = append(channelInfo.Forwards, &PaymentInfo{Direction: ChannelDirections[0], Status: forward.Status})
}
switch forward.Status {
case "settled", "failed":
// do nothings
continue
case "local_failed":
// store the information about the failure
if len(channelInfo.Forwards) == 0 {
continue
}
paymentInfo := channelInfo.Forwards[len(channelInfo.Forwards)-1]
paymentInfo.FailureReason = forward.FailReason
paymentInfo.FailureCode = forward.FailCode
default:
return nil, fmt.Errorf("Status %s unexpected", forward.Status)
}
}
//TODO Adding support for the dual founding channels.
return &channelInfo, nil
}