2022-07-11 17:49:47 +00:00
|
|
|
package metrics
|
|
|
|
|
|
|
|
import (
|
2022-11-28 10:30:14 +00:00
|
|
|
"context"
|
2022-07-11 17:49:47 +00:00
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/go-logr/logr"
|
|
|
|
"github.com/kyverno/kyverno/pkg/config"
|
2023-06-19 09:09:08 +00:00
|
|
|
"go.opentelemetry.io/otel"
|
2022-12-06 15:41:00 +00:00
|
|
|
"go.opentelemetry.io/otel/metric"
|
|
|
|
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
|
2022-07-11 17:49:47 +00:00
|
|
|
"k8s.io/client-go/kubernetes"
|
|
|
|
)
|
|
|
|
|
|
|
|
func InitMetrics(
|
2022-11-28 10:30:14 +00:00
|
|
|
ctx context.Context,
|
2022-07-11 17:49:47 +00:00
|
|
|
disableMetricsExport bool,
|
2023-06-19 09:09:08 +00:00
|
|
|
otelProvider string,
|
2022-07-11 17:49:47 +00:00
|
|
|
metricsAddr string,
|
|
|
|
otelCollector string,
|
2022-11-25 13:14:55 +00:00
|
|
|
metricsConfiguration config.MetricsConfiguration,
|
2022-07-11 17:49:47 +00:00
|
|
|
transportCreds string,
|
|
|
|
kubeClient kubernetes.Interface,
|
2022-12-06 15:41:00 +00:00
|
|
|
logger logr.Logger,
|
|
|
|
) (MetricsConfigManager, *http.ServeMux, *sdkmetric.MeterProvider, error) {
|
2022-07-11 17:49:47 +00:00
|
|
|
var err error
|
|
|
|
var metricsServerMux *http.ServeMux
|
|
|
|
if !disableMetricsExport {
|
2022-12-06 15:41:00 +00:00
|
|
|
var meterProvider metric.MeterProvider
|
2023-06-19 09:09:08 +00:00
|
|
|
if otelProvider == "grpc" {
|
2022-07-11 17:49:47 +00:00
|
|
|
endpoint := otelCollector + metricsAddr
|
2022-12-06 15:41:00 +00:00
|
|
|
meterProvider, err = NewOTLPGRPCConfig(
|
2022-11-28 10:30:14 +00:00
|
|
|
ctx,
|
2022-07-11 17:49:47 +00:00
|
|
|
endpoint,
|
|
|
|
transportCreds,
|
|
|
|
kubeClient,
|
2022-12-06 15:41:00 +00:00
|
|
|
logger,
|
2023-10-12 09:50:27 +00:00
|
|
|
metricsConfiguration,
|
2022-07-11 17:49:47 +00:00
|
|
|
)
|
|
|
|
if err != nil {
|
2022-11-17 05:29:32 +00:00
|
|
|
return nil, nil, nil, err
|
2022-07-11 17:49:47 +00:00
|
|
|
}
|
2023-06-19 09:09:08 +00:00
|
|
|
} else if otelProvider == "prometheus" {
|
2023-10-12 09:50:27 +00:00
|
|
|
meterProvider, metricsServerMux, err = NewPrometheusConfig(ctx, logger, metricsConfiguration)
|
2022-07-11 17:49:47 +00:00
|
|
|
if err != nil {
|
2022-12-06 15:41:00 +00:00
|
|
|
return nil, nil, nil, err
|
2022-07-11 17:49:47 +00:00
|
|
|
}
|
|
|
|
}
|
2022-12-06 15:41:00 +00:00
|
|
|
if meterProvider != nil {
|
2023-06-19 09:09:08 +00:00
|
|
|
otel.SetMeterProvider(meterProvider)
|
2022-12-06 15:41:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
metricsConfig := MetricsConfig{
|
|
|
|
Log: logger,
|
|
|
|
config: metricsConfiguration,
|
|
|
|
}
|
2023-06-19 09:09:08 +00:00
|
|
|
err = metricsConfig.initializeMetrics(otel.GetMeterProvider())
|
2022-12-06 15:41:00 +00:00
|
|
|
if err != nil {
|
|
|
|
logger.Error(err, "Failed initializing metrics")
|
|
|
|
return nil, nil, nil, err
|
2022-07-11 17:49:47 +00:00
|
|
|
}
|
2022-12-06 15:41:00 +00:00
|
|
|
return &metricsConfig, metricsServerMux, nil, nil
|
2022-07-11 17:49:47 +00:00
|
|
|
}
|