github.com/cilium/cilium@v1.16.2/pkg/hubble/metrics/api/registry.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright Authors of Hubble
     3  
     4  package api
     5  
     6  import (
     7  	"fmt"
     8  
     9  	"github.com/prometheus/client_golang/prometheus"
    10  	"github.com/sirupsen/logrus"
    11  
    12  	"github.com/cilium/cilium/pkg/lock"
    13  )
    14  
    15  // Registry holds a set of registered metric handlers
    16  type Registry struct {
    17  	log      logrus.FieldLogger
    18  	mutex    lock.Mutex
    19  	handlers map[string]Plugin
    20  }
    21  
    22  // NewRegistry returns a new Registry
    23  func NewRegistry(log logrus.FieldLogger) *Registry {
    24  	return &Registry{
    25  		log: log,
    26  	}
    27  }
    28  
    29  // Register registers a metrics handler plugin with the manager. After
    30  // registration, the metrics handler plugin can be enabled via
    31  // HandlerManager.ConfigureHandlers().
    32  func (r *Registry) Register(name string, p Plugin) {
    33  	r.mutex.Lock()
    34  	if r.handlers == nil {
    35  		r.handlers = map[string]Plugin{}
    36  	}
    37  	r.handlers[name] = p
    38  	r.mutex.Unlock()
    39  }
    40  
    41  type NamedHandler struct {
    42  	Name    string
    43  	Options Options
    44  	Handler Handler
    45  }
    46  
    47  // ConfigureHandlers enables a set of metric handlers and initializes them.
    48  // Only metrics handlers which have been previously registered via the
    49  // Register() function can be configured.
    50  func (r *Registry) ConfigureHandlers(registry *prometheus.Registry, enabled Map) (*Handlers, error) {
    51  	r.mutex.Lock()
    52  	defer r.mutex.Unlock()
    53  
    54  	var enabledHandlers []NamedHandler
    55  	for name, opts := range enabled {
    56  		plugin, ok := r.handlers[name]
    57  		if !ok {
    58  			return nil, fmt.Errorf("metric '%s' does not exist", name)
    59  		}
    60  
    61  		if cp, ok := plugin.(PluginConflicts); ok {
    62  			for _, conflict := range cp.ConflictingPlugins() {
    63  				if _, conflictExists := enabled[conflict]; conflictExists {
    64  					return nil, fmt.Errorf("plugin %s conflicts with plugin %s", name, conflict)
    65  				}
    66  			}
    67  		}
    68  
    69  		h := NamedHandler{
    70  			Name:    name,
    71  			Options: opts,
    72  			Handler: plugin.NewHandler(),
    73  		}
    74  		enabledHandlers = append(enabledHandlers, h)
    75  	}
    76  
    77  	return NewHandlers(r.log, registry, enabledHandlers)
    78  }