github.com/verrazzano/verrazzano@v1.7.0/tools/psr/backend/metrics/collector.go (about)

     1  // Copyright (c) 2022, Oracle and/or its affiliates.
     2  // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
     3  
     4  package metrics
     5  
     6  import (
     7  	"github.com/prometheus/client_golang/prometheus"
     8  	"github.com/verrazzano/verrazzano/tools/psr/backend/spi"
     9  	"sync/atomic"
    10  )
    11  
    12  type workerCollector struct {
    13  	providers []spi.WorkerMetricsProvider
    14  }
    15  
    16  func (rc workerCollector) Describe(ch chan<- *prometheus.Desc) {
    17  	// Loop through the metrics providers. Usually it is just the runner and a worker
    18  	for _, p := range rc.providers {
    19  		// Get the metrics for the provider and send the descriptor to the channel
    20  		dd := p.GetMetricDescList()
    21  		for i := range dd {
    22  			ch <- &dd[i]
    23  		}
    24  	}
    25  }
    26  
    27  func (rc workerCollector) Collect(ch chan<- prometheus.Metric) {
    28  	// Loop through the metrics providers. Usually it is just the runner and a worker
    29  	for _, p := range rc.providers {
    30  		// Get the metrics for the provider and send the metric to the channel
    31  		mm := p.GetMetricList()
    32  		for i := range mm {
    33  			ch <- mm[i]
    34  		}
    35  	}
    36  }
    37  
    38  // MetricItem contains the information for a single metric
    39  type MetricItem struct {
    40  	Val         int64
    41  	Desc        *prometheus.Desc
    42  	Name        string
    43  	Help        string
    44  	Type        prometheus.ValueType
    45  	ConstLabels prometheus.Labels
    46  	VarLabels   []string
    47  }
    48  
    49  // BuildMetric builds the prometheus metrics from the MetricItem
    50  func (m *MetricItem) BuildMetric() prometheus.Metric {
    51  	return prometheus.MustNewConstMetric(
    52  		m.Desc,
    53  		m.Type,
    54  		float64(atomic.LoadInt64(&m.Val)),
    55  	)
    56  }
    57  
    58  func BuildMetricDescList(metrics []*MetricItem, labels map[string]string, workerMetricsName string) []prometheus.Desc {
    59  	var descList []prometheus.Desc
    60  	for _, metric := range metrics {
    61  		metric.ConstLabels = labels
    62  		descList = append(descList, *metric.BuildMetricDesc(workerMetricsName))
    63  	}
    64  	return descList
    65  }
    66  
    67  // BuildMetricDesc builds the MetricItem description from info about the metric and worker
    68  func (m *MetricItem) BuildMetricDesc(workerMetricsName string) *prometheus.Desc {
    69  	d := prometheus.NewDesc(
    70  		prometheus.BuildFQName(PsrNamespace, workerMetricsName, m.Name),
    71  		m.Help,
    72  		m.VarLabels,
    73  		m.ConstLabels,
    74  	)
    75  	m.Desc = d
    76  	return d
    77  }