github.com/cilium/cilium@v1.16.2/operator/metrics/legacy.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright Authors of Cilium
     3  
     4  package metrics
     5  
     6  import (
     7  	"github.com/prometheus/client_golang/prometheus"
     8  	dto "github.com/prometheus/client_model/go"
     9  
    10  	"github.com/cilium/cilium/api/v1/operator/models"
    11  )
    12  
    13  // Registry is the global prometheus registry for cilium-operator metrics.
    14  var Registry RegisterGatherer
    15  
    16  type RegisterGatherer interface {
    17  	prometheus.Registerer
    18  	prometheus.Gatherer
    19  }
    20  
    21  // DumpMetrics gets the current Cilium operator metrics and dumps all into a
    22  // Metrics structure. If metrics cannot be retrieved, returns an error.
    23  func DumpMetrics() ([]*models.Metric, error) {
    24  	result := []*models.Metric{}
    25  	if Registry == nil {
    26  		return result, nil
    27  	}
    28  
    29  	currentMetrics, err := Registry.Gather()
    30  	if err != nil {
    31  		return result, err
    32  	}
    33  
    34  	for _, val := range currentMetrics {
    35  
    36  		metricName := val.GetName()
    37  		metricType := val.GetType()
    38  
    39  		for _, metricLabel := range val.Metric {
    40  			labelPairs := metricLabel.GetLabel()
    41  			labels := make(map[string]string, len(labelPairs))
    42  			for _, label := range labelPairs {
    43  				labels[label.GetName()] = label.GetValue()
    44  			}
    45  
    46  			var value float64
    47  			switch metricType {
    48  			case dto.MetricType_COUNTER:
    49  				value = metricLabel.Counter.GetValue()
    50  			case dto.MetricType_GAUGE:
    51  				value = metricLabel.GetGauge().GetValue()
    52  			case dto.MetricType_UNTYPED:
    53  				value = metricLabel.GetUntyped().GetValue()
    54  			case dto.MetricType_SUMMARY:
    55  				value = metricLabel.GetSummary().GetSampleSum()
    56  			case dto.MetricType_HISTOGRAM:
    57  				value = metricLabel.GetHistogram().GetSampleSum()
    58  			default:
    59  				continue
    60  			}
    61  
    62  			metric := &models.Metric{
    63  				Name:   metricName,
    64  				Labels: labels,
    65  				Value:  value,
    66  			}
    67  			result = append(result, metric)
    68  		}
    69  	}
    70  
    71  	return result, nil
    72  }