github.com/safing/portbase@v0.19.5/metrics/metric_export.go (about)

     1  package metrics
     2  
     3  import (
     4  	"github.com/safing/portbase/api"
     5  )
     6  
     7  // UIntMetric is an interface for special functions of uint metrics.
     8  type UIntMetric interface {
     9  	CurrentValue() uint64
    10  }
    11  
    12  // FloatMetric is an interface for special functions of float metrics.
    13  type FloatMetric interface {
    14  	CurrentValue() float64
    15  }
    16  
    17  // MetricExport is used to export a metric and its current value.
    18  type MetricExport struct {
    19  	Metric
    20  	CurrentValue any
    21  }
    22  
    23  // ExportMetrics exports all registered metrics.
    24  func ExportMetrics(requestPermission api.Permission) []*MetricExport {
    25  	registryLock.RLock()
    26  	defer registryLock.RUnlock()
    27  
    28  	export := make([]*MetricExport, 0, len(registry))
    29  	for _, metric := range registry {
    30  		// Check permission.
    31  		if requestPermission < metric.Opts().Permission {
    32  			continue
    33  		}
    34  
    35  		// Add metric with current value.
    36  		export = append(export, &MetricExport{
    37  			Metric:       metric,
    38  			CurrentValue: getCurrentValue(metric),
    39  		})
    40  	}
    41  
    42  	return export
    43  }
    44  
    45  // ExportValues exports the values of all supported metrics.
    46  func ExportValues(requestPermission api.Permission, internalOnly bool) map[string]any {
    47  	registryLock.RLock()
    48  	defer registryLock.RUnlock()
    49  
    50  	export := make(map[string]any, len(registry))
    51  	for _, metric := range registry {
    52  		// Check permission.
    53  		if requestPermission < metric.Opts().Permission {
    54  			continue
    55  		}
    56  
    57  		// Get Value.
    58  		v := getCurrentValue(metric)
    59  		if v == nil {
    60  			continue
    61  		}
    62  
    63  		// Get ID.
    64  		var id string
    65  		switch {
    66  		case metric.Opts().InternalID != "":
    67  			id = metric.Opts().InternalID
    68  		case internalOnly:
    69  			continue
    70  		default:
    71  			id = metric.LabeledID()
    72  		}
    73  
    74  		// Add to export
    75  		export[id] = v
    76  	}
    77  
    78  	return export
    79  }
    80  
    81  func getCurrentValue(metric Metric) any {
    82  	if m, ok := metric.(UIntMetric); ok {
    83  		return m.CurrentValue()
    84  	}
    85  	if m, ok := metric.(FloatMetric); ok {
    86  		return m.CurrentValue()
    87  	}
    88  	return nil
    89  }