knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/observability/metrics/prometheus_enabled.go (about)

     1  //go:build !noprometheus
     2  
     3  /*
     4  Copyright 2025 The Knative Authors
     5  
     6  Licensed under the Apache License, Version 2.0 (the "License");
     7  you may not use this file except in compliance with the License.
     8  You may obtain a copy of the License at
     9  
    10      http://www.apache.org/licenses/LICENSE-2.0
    11  
    12  Unless required by applicable law or agreed to in writing, software
    13  distributed under the License is distributed on an "AS IS" BASIS,
    14  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    15  See the License for the specific language governing permissions and
    16  limitations under the License.
    17  */
    18  
    19  package metrics
    20  
    21  import (
    22  	"context"
    23  	"errors"
    24  	"fmt"
    25  	"net"
    26  	"net/http"
    27  
    28  	"github.com/prometheus/otlptranslator"
    29  	otelprom "go.opentelemetry.io/otel/exporters/prometheus"
    30  	sdkmetric "go.opentelemetry.io/otel/sdk/metric"
    31  	"knative.dev/pkg/observability/metrics/prometheus"
    32  )
    33  
    34  func buildPrometheus(_ context.Context, cfg Config) (sdkmetric.Reader, shutdownFunc, error) {
    35  	r, err := otelprom.New(
    36  		otelprom.WithTranslationStrategy(otlptranslator.UnderscoreEscapingWithSuffixes),
    37  	)
    38  	if err != nil {
    39  		return nil, noopFunc, fmt.Errorf("unable to create otel prometheus exporter: %w", err)
    40  	}
    41  
    42  	var opts []prometheus.ServerOption
    43  
    44  	if cfg.Endpoint != "" {
    45  		host, port, err := net.SplitHostPort(cfg.Endpoint)
    46  		if err != nil {
    47  			return nil, noopFunc, fmt.Errorf(
    48  				`metrics-endpoint %q for prometheus exporter should be "host:port", "host%%zone:port", "[host]:port" or "[host%%zone]:port"`,
    49  				cfg.Endpoint,
    50  			)
    51  		}
    52  
    53  		opts = append(opts,
    54  			prometheus.WithHost(host),
    55  			prometheus.WithPort(port),
    56  		)
    57  	}
    58  
    59  	server, err := prometheus.NewServer(opts...)
    60  	if err != nil {
    61  		return nil, noopFunc, fmt.Errorf("create prometheus metrics server: %w", err)
    62  	}
    63  
    64  	go func() {
    65  		if err := server.Serve(); err != nil && !errors.Is(err, http.ErrServerClosed) {
    66  			fmt.Printf("metrics server error: %v\n", err)
    67  		}
    68  	}()
    69  
    70  	return r, server.Shutdown, nil
    71  }