2018-01-30 11:51:48 +00:00
|
|
|
package node
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
|
2018-03-20 18:35:28 +00:00
|
|
|
"github.com/ethereum/go-ethereum/log"
|
2018-01-30 11:51:48 +00:00
|
|
|
"github.com/ethereum/go-ethereum/node"
|
|
|
|
"github.com/ethereum/go-ethereum/p2p"
|
|
|
|
)
|
|
|
|
|
2018-03-20 18:35:28 +00:00
|
|
|
// All general log messages in this package should be routed through this logger.
|
|
|
|
var logger = log.New("package", "status-go/metrics/node")
|
|
|
|
|
2018-01-30 11:51:48 +00:00
|
|
|
// SubscribeServerEvents subscribes to server and listens to
|
|
|
|
// PeerEventTypeAdd and PeerEventTypeDrop events.
|
|
|
|
func SubscribeServerEvents(ctx context.Context, node *node.Node) error {
|
|
|
|
server := node.Server()
|
2018-03-20 18:35:28 +00:00
|
|
|
|
2018-01-30 11:51:48 +00:00
|
|
|
if server == nil {
|
|
|
|
return errors.New("server is unavailable")
|
|
|
|
}
|
|
|
|
|
|
|
|
ch := make(chan *p2p.PeerEvent, server.MaxPeers)
|
|
|
|
subscription := server.SubscribeEvents(ch)
|
2018-11-12 09:27:09 +00:00
|
|
|
defer subscription.Unsubscribe()
|
2018-01-30 11:51:48 +00:00
|
|
|
|
2018-03-20 18:35:28 +00:00
|
|
|
logger.Debug("Subscribed to server events")
|
2018-01-30 11:51:48 +00:00
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case event := <-ch:
|
|
|
|
if isAddDropPeerEvent(event.Type) {
|
2018-05-22 10:26:03 +00:00
|
|
|
if err := updateNodeMetrics(node, event.Type); err != nil {
|
2019-10-22 17:32:05 +00:00
|
|
|
logger.Error("failed to update node metrics", "err", err)
|
2018-05-22 10:26:03 +00:00
|
|
|
}
|
2018-01-30 11:51:48 +00:00
|
|
|
}
|
|
|
|
case err := <-subscription.Err():
|
|
|
|
if err != nil {
|
2018-05-22 10:26:03 +00:00
|
|
|
logger.Error("Subscription failed", "err", err)
|
2018-01-30 11:51:48 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
case <-ctx.Done():
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func isAddDropPeerEvent(eventType p2p.PeerEventType) bool {
|
|
|
|
return eventType == p2p.PeerEventTypeAdd || eventType == p2p.PeerEventTypeDrop
|
|
|
|
}
|