2022-10-16 13:33:46 +02:00
|
|
|
// Package metrics gather anonymous information about the usage of NetBird management
|
|
|
|
package metrics
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
2022-11-18 16:35:13 +01:00
|
|
|
"sort"
|
2022-10-16 13:33:46 +02:00
|
|
|
"strings"
|
|
|
|
"time"
|
2023-03-15 07:54:51 +01:00
|
|
|
|
|
|
|
"github.com/hashicorp/go-version"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
|
|
|
|
"github.com/netbirdio/netbird/management/server"
|
|
|
|
nbversion "github.com/netbirdio/netbird/version"
|
2022-10-16 13:33:46 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
// PayloadEvent identifies an event type
|
|
|
|
PayloadEvent = "self-hosted stats"
|
2022-10-22 11:50:21 +02:00
|
|
|
// payloadEndpoint metrics defaultEndpoint to send anonymous data
|
2022-10-16 13:33:46 +02:00
|
|
|
payloadEndpoint = "https://metrics.netbird.io"
|
|
|
|
// defaultPushInterval default interval to push metrics
|
|
|
|
defaultPushInterval = 24 * time.Hour
|
|
|
|
// requestTimeout http request timeout
|
|
|
|
requestTimeout = 30 * time.Second
|
|
|
|
)
|
|
|
|
|
|
|
|
type getTokenResponse struct {
|
|
|
|
PublicAPIToken string `json:"public_api_token"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type pushPayload struct {
|
|
|
|
APIKey string `json:"api_key"`
|
|
|
|
DistinctID string `json:"distinct_id"`
|
|
|
|
Event string `json:"event"`
|
|
|
|
Properties properties `json:"properties"`
|
|
|
|
Timestamp time.Time `json:"timestamp"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// properties metrics to push
|
|
|
|
type properties map[string]interface{}
|
|
|
|
|
|
|
|
// DataSource metric data source
|
|
|
|
type DataSource interface {
|
|
|
|
GetAllAccounts() []*server.Account
|
2023-10-16 11:19:39 +02:00
|
|
|
GetStoreEngine() server.StoreEngine
|
2022-10-16 13:33:46 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// ConnManager peer connection manager that holds state for current active connections
|
|
|
|
type ConnManager interface {
|
|
|
|
GetAllConnectedPeers() map[string]struct{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Worker metrics collector and pusher
|
|
|
|
type Worker struct {
|
|
|
|
ctx context.Context
|
|
|
|
id string
|
2023-07-22 19:30:59 +02:00
|
|
|
idpManager string
|
2022-10-16 13:33:46 +02:00
|
|
|
dataSource DataSource
|
|
|
|
connManager ConnManager
|
|
|
|
startupTime time.Time
|
|
|
|
lastRun time.Time
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewWorker returns a metrics worker
|
2023-07-22 19:30:59 +02:00
|
|
|
func NewWorker(ctx context.Context, id string, dataSource DataSource, connManager ConnManager, idpManager string) *Worker {
|
2022-10-16 13:33:46 +02:00
|
|
|
currentTime := time.Now()
|
|
|
|
return &Worker{
|
|
|
|
ctx: ctx,
|
|
|
|
id: id,
|
2023-07-22 19:30:59 +02:00
|
|
|
idpManager: idpManager,
|
2022-10-16 13:33:46 +02:00
|
|
|
dataSource: dataSource,
|
|
|
|
connManager: connManager,
|
|
|
|
startupTime: currentTime,
|
|
|
|
lastRun: currentTime,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Run runs the metrics worker
|
|
|
|
func (w *Worker) Run() {
|
|
|
|
pushTicker := time.NewTicker(defaultPushInterval)
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-w.ctx.Done():
|
|
|
|
return
|
|
|
|
case <-pushTicker.C:
|
|
|
|
err := w.sendMetrics()
|
|
|
|
if err != nil {
|
|
|
|
log.Error(err)
|
|
|
|
}
|
2022-11-18 16:35:13 +01:00
|
|
|
w.lastRun = time.Now()
|
2022-10-16 13:33:46 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *Worker) sendMetrics() error {
|
|
|
|
ctx, cancel := context.WithTimeout(w.ctx, requestTimeout)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
apiKey, err := getAPIKey(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
payload := w.generatePayload(apiKey)
|
|
|
|
|
|
|
|
payloadString, err := buildMetricsPayload(payload)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
httpClient := http.Client{}
|
|
|
|
|
|
|
|
exportJobReq, err := createPostRequest(ctx, payloadEndpoint+"/capture/", payloadString)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("unable to create metrics post request %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
jobResp, err := httpClient.Do(exportJobReq)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("unable to push metrics %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
defer func() {
|
|
|
|
err = jobResp.Body.Close()
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("error while closing update metrics response body: %v", err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
if jobResp.StatusCode != 200 {
|
|
|
|
return fmt.Errorf("unable to push anonymous metrics, got statusCode %d", jobResp.StatusCode)
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Infof("sent anonymous metrics, next push will happen in %s. "+
|
|
|
|
"You can disable these metrics by running with flag --disable-anonymous-metrics,"+
|
|
|
|
" see more information at https://netbird.io/docs/FAQ/metrics-collection", defaultPushInterval)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *Worker) generatePayload(apiKey string) pushPayload {
|
|
|
|
properties := w.generateProperties()
|
|
|
|
|
|
|
|
return pushPayload{
|
|
|
|
APIKey: apiKey,
|
|
|
|
DistinctID: w.id,
|
|
|
|
Event: PayloadEvent,
|
|
|
|
Properties: properties,
|
|
|
|
Timestamp: time.Now(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *Worker) generateProperties() properties {
|
|
|
|
var (
|
2023-09-05 23:04:14 +02:00
|
|
|
uptime float64
|
|
|
|
accounts int
|
|
|
|
expirationEnabled int
|
|
|
|
users int
|
|
|
|
serviceUsers int
|
|
|
|
pats int
|
|
|
|
peers int
|
|
|
|
peersSSHEnabled int
|
|
|
|
setupKeysUsage int
|
|
|
|
ephemeralPeersSKs int
|
|
|
|
ephemeralPeersSKUsage int
|
|
|
|
activePeersLastDay int
|
|
|
|
osPeers map[string]int
|
|
|
|
userPeers int
|
|
|
|
rules int
|
|
|
|
rulesProtocol map[string]int
|
|
|
|
rulesDirection map[string]int
|
|
|
|
groups int
|
|
|
|
routes int
|
2023-10-02 12:10:12 +02:00
|
|
|
routesWithRGGroups int
|
2023-09-05 23:04:14 +02:00
|
|
|
nameservers int
|
|
|
|
uiClient int
|
|
|
|
version string
|
|
|
|
peerActiveVersions []string
|
|
|
|
osUIClients map[string]int
|
2022-10-16 13:33:46 +02:00
|
|
|
)
|
|
|
|
start := time.Now()
|
|
|
|
metricsProperties := make(properties)
|
|
|
|
osPeers = make(map[string]int)
|
2022-11-18 16:35:13 +01:00
|
|
|
osUIClients = make(map[string]int)
|
2023-05-30 18:53:23 +02:00
|
|
|
rulesProtocol = make(map[string]int)
|
|
|
|
rulesDirection = make(map[string]int)
|
2022-10-16 13:33:46 +02:00
|
|
|
uptime = time.Since(w.startupTime).Seconds()
|
|
|
|
connections := w.connManager.GetAllConnectedPeers()
|
2023-03-15 07:54:51 +01:00
|
|
|
version = nbversion.NetbirdVersion()
|
2022-10-16 13:33:46 +02:00
|
|
|
|
|
|
|
for _, account := range w.dataSource.GetAllAccounts() {
|
|
|
|
accounts++
|
2023-05-30 18:49:50 +02:00
|
|
|
|
|
|
|
if account.Settings.PeerLoginExpirationEnabled {
|
|
|
|
expirationEnabled++
|
|
|
|
}
|
|
|
|
|
2022-10-16 13:33:46 +02:00
|
|
|
groups = groups + len(account.Groups)
|
|
|
|
routes = routes + len(account.Routes)
|
2023-10-02 12:10:12 +02:00
|
|
|
for _, route := range account.Routes {
|
|
|
|
if len(route.PeerGroups) > 0 {
|
|
|
|
routesWithRGGroups++
|
|
|
|
}
|
|
|
|
}
|
2022-10-16 13:33:46 +02:00
|
|
|
nameservers = nameservers + len(account.NameServerGroups)
|
|
|
|
|
2023-05-30 19:09:16 +02:00
|
|
|
for _, policy := range account.Policies {
|
|
|
|
for _, rule := range policy.Rules {
|
2023-05-30 19:36:09 +02:00
|
|
|
rules++
|
2023-05-30 19:09:16 +02:00
|
|
|
rulesProtocol[string(rule.Protocol)]++
|
|
|
|
if rule.Bidirectional {
|
|
|
|
rulesDirection["bidirectional"]++
|
|
|
|
} else {
|
|
|
|
rulesDirection["oneway"]++
|
|
|
|
}
|
2023-05-30 18:49:50 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-30 16:22:34 +02:00
|
|
|
for _, user := range account.Users {
|
|
|
|
if user.IsServiceUser {
|
|
|
|
serviceUsers++
|
|
|
|
} else {
|
|
|
|
users++
|
|
|
|
}
|
2023-05-30 19:44:40 +02:00
|
|
|
pats += len(user.PATs)
|
2023-05-30 16:22:34 +02:00
|
|
|
}
|
|
|
|
|
2022-10-16 13:33:46 +02:00
|
|
|
for _, key := range account.SetupKeys {
|
|
|
|
setupKeysUsage = setupKeysUsage + key.UsedTimes
|
2023-09-05 23:04:14 +02:00
|
|
|
if key.Ephemeral {
|
|
|
|
ephemeralPeersSKs++
|
|
|
|
ephemeralPeersSKUsage = ephemeralPeersSKUsage + key.UsedTimes
|
|
|
|
}
|
2022-10-16 13:33:46 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, peer := range account.Peers {
|
|
|
|
peers++
|
2023-05-30 18:49:50 +02:00
|
|
|
|
|
|
|
if peer.SSHEnabled {
|
|
|
|
peersSSHEnabled++
|
|
|
|
}
|
|
|
|
|
2022-11-18 16:35:13 +01:00
|
|
|
if peer.SetupKey == "" {
|
2022-10-16 13:33:46 +02:00
|
|
|
userPeers++
|
|
|
|
}
|
|
|
|
|
2022-10-26 14:48:40 +02:00
|
|
|
osKey := strings.ToLower(fmt.Sprintf("peer_os_%s", peer.Meta.GoOS))
|
|
|
|
osCount := osPeers[osKey]
|
|
|
|
osPeers[osKey] = osCount + 1
|
|
|
|
|
2022-11-18 16:35:13 +01:00
|
|
|
if peer.Meta.UIVersion != "" {
|
|
|
|
uiClient++
|
|
|
|
uiOSKey := strings.ToLower(fmt.Sprintf("ui_client_os_%s", peer.Meta.GoOS))
|
|
|
|
osUICount := osUIClients[uiOSKey]
|
|
|
|
osUIClients[uiOSKey] = osUICount + 1
|
|
|
|
}
|
|
|
|
|
2023-02-03 10:33:28 +01:00
|
|
|
_, connected := connections[peer.ID]
|
2022-10-16 13:33:46 +02:00
|
|
|
if connected || peer.Status.LastSeen.After(w.lastRun) {
|
|
|
|
activePeersLastDay++
|
2022-10-26 14:48:40 +02:00
|
|
|
osActiveKey := osKey + "_active"
|
|
|
|
osActiveCount := osPeers[osActiveKey]
|
|
|
|
osPeers[osActiveKey] = osActiveCount + 1
|
2022-11-18 16:35:13 +01:00
|
|
|
peerActiveVersions = append(peerActiveVersions, peer.Meta.WtVersion)
|
2022-10-16 13:33:46 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-18 16:35:13 +01:00
|
|
|
minActivePeerVersion, maxActivePeerVersion := getMinMaxVersion(peerActiveVersions)
|
2022-10-16 13:33:46 +02:00
|
|
|
metricsProperties["uptime"] = uptime
|
|
|
|
metricsProperties["accounts"] = accounts
|
|
|
|
metricsProperties["users"] = users
|
2023-05-30 16:40:48 +02:00
|
|
|
metricsProperties["service_users"] = serviceUsers
|
2023-05-30 16:22:34 +02:00
|
|
|
metricsProperties["pats"] = pats
|
2022-10-16 13:33:46 +02:00
|
|
|
metricsProperties["peers"] = peers
|
2023-05-30 18:49:50 +02:00
|
|
|
metricsProperties["peers_ssh_enabled"] = peersSSHEnabled
|
|
|
|
metricsProperties["peers_login_expiration_enabled"] = expirationEnabled
|
2022-10-16 13:33:46 +02:00
|
|
|
metricsProperties["setup_keys_usage"] = setupKeysUsage
|
2023-09-05 23:04:14 +02:00
|
|
|
metricsProperties["ephemeral_peers_setup_keys"] = ephemeralPeersSKs
|
|
|
|
metricsProperties["ephemeral_peers_setup_keys_usage"] = ephemeralPeersSKUsage
|
2022-10-16 13:33:46 +02:00
|
|
|
metricsProperties["active_peers_last_day"] = activePeersLastDay
|
|
|
|
metricsProperties["user_peers"] = userPeers
|
|
|
|
metricsProperties["rules"] = rules
|
|
|
|
metricsProperties["groups"] = groups
|
|
|
|
metricsProperties["routes"] = routes
|
2023-10-02 12:10:12 +02:00
|
|
|
metricsProperties["routes_with_routing_groups"] = routesWithRGGroups
|
2022-10-16 13:33:46 +02:00
|
|
|
metricsProperties["nameservers"] = nameservers
|
|
|
|
metricsProperties["version"] = version
|
2022-11-18 16:35:13 +01:00
|
|
|
metricsProperties["min_active_peer_version"] = minActivePeerVersion
|
|
|
|
metricsProperties["max_active_peer_version"] = maxActivePeerVersion
|
|
|
|
metricsProperties["ui_clients"] = uiClient
|
2023-07-22 19:30:59 +02:00
|
|
|
metricsProperties["idp_manager"] = w.idpManager
|
2023-10-16 11:19:39 +02:00
|
|
|
metricsProperties["store_engine"] = w.dataSource.GetStoreEngine()
|
2023-05-30 19:07:00 +02:00
|
|
|
|
|
|
|
for protocol, count := range rulesProtocol {
|
|
|
|
metricsProperties["rules_protocol_"+protocol] = count
|
|
|
|
}
|
|
|
|
|
|
|
|
for direction, count := range rulesDirection {
|
|
|
|
metricsProperties["rules_direction_"+direction] = count
|
|
|
|
}
|
|
|
|
|
2022-10-16 13:33:46 +02:00
|
|
|
for os, count := range osPeers {
|
|
|
|
metricsProperties[os] = count
|
|
|
|
}
|
|
|
|
|
2022-11-18 16:35:13 +01:00
|
|
|
for os, count := range osUIClients {
|
|
|
|
metricsProperties[os] = count
|
|
|
|
}
|
|
|
|
|
2022-10-16 13:33:46 +02:00
|
|
|
metricsProperties["metric_generation_time"] = time.Since(start).Milliseconds()
|
|
|
|
|
|
|
|
return metricsProperties
|
|
|
|
}
|
|
|
|
|
|
|
|
func getAPIKey(ctx context.Context) (string, error) {
|
|
|
|
|
|
|
|
httpClient := http.Client{}
|
|
|
|
|
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, payloadEndpoint+"/GetToken", nil)
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("unable to create request for metrics public api token %v", err)
|
|
|
|
}
|
|
|
|
response, err := httpClient.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("unable to request metrics public api token %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
defer func() {
|
|
|
|
err = response.Body.Close()
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("error while closing metrics token response body: %v", err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
if response.StatusCode != 200 {
|
|
|
|
return "", fmt.Errorf("unable to retrieve metrics token, statusCode %d", response.StatusCode)
|
|
|
|
}
|
|
|
|
|
|
|
|
body, err := io.ReadAll(response.Body)
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("coudln't get metrics token response; %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
var tokenResponse getTokenResponse
|
|
|
|
|
|
|
|
err = json.Unmarshal(body, &tokenResponse)
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("coudln't parse metrics public api token; %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return tokenResponse.PublicAPIToken, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func buildMetricsPayload(payload pushPayload) (string, error) {
|
|
|
|
str, err := json.Marshal(payload)
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("unable to marshal metrics payload, got err: %v", err)
|
|
|
|
}
|
|
|
|
return string(str), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func createPostRequest(ctx context.Context, endpoint string, payloadStr string) (*http.Request, error) {
|
|
|
|
reqURL := endpoint
|
|
|
|
|
|
|
|
payload := strings.NewReader(payloadStr)
|
|
|
|
|
|
|
|
req, err := http.NewRequestWithContext(ctx, "POST", reqURL, payload)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
req.Header.Add("content-type", "application/json")
|
|
|
|
|
|
|
|
return req, nil
|
|
|
|
}
|
2022-11-18 16:35:13 +01:00
|
|
|
|
|
|
|
func getMinMaxVersion(inputList []string) (string, string) {
|
|
|
|
versions := make([]*version.Version, 0)
|
|
|
|
|
|
|
|
for _, raw := range inputList {
|
2023-11-27 13:01:00 +01:00
|
|
|
if raw != "" && nbversion.SemverRegexp.MatchString(raw) {
|
2022-11-18 16:35:13 +01:00
|
|
|
v, err := version.NewVersion(raw)
|
|
|
|
if err == nil {
|
|
|
|
versions = append(versions, v)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
switch len(versions) {
|
|
|
|
case 0:
|
|
|
|
return "", ""
|
|
|
|
case 1:
|
|
|
|
v := versions[0].String()
|
|
|
|
return v, v
|
|
|
|
default:
|
|
|
|
sort.Sort(version.Collection(versions))
|
|
|
|
return versions[0].String(), versions[len(versions)-1].String()
|
|
|
|
}
|
|
|
|
}
|