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

     1  /*
     2  Copyright 2025 The Knative Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package tracing
    18  
    19  import (
    20  	"errors"
    21  	"fmt"
    22  
    23  	configmap "knative.dev/pkg/configmap/parser"
    24  )
    25  
    26  const (
    27  	ProtocolGRPC         = "grpc"
    28  	ProtocolHTTPProtobuf = "http/protobuf"
    29  	ProtocolNone         = "none"
    30  	ProtocolStdout       = "stdout"
    31  )
    32  
    33  type Config struct {
    34  	Protocol     string  `json:"protocol,omitempty"`
    35  	Endpoint     string  `json:"endpoint,omitempty"`
    36  	SamplingRate float64 `json:"samplingRate,omitempty"`
    37  }
    38  
    39  func (c *Config) Validate() error {
    40  	switch c.Protocol {
    41  	case ProtocolGRPC, ProtocolHTTPProtobuf:
    42  		if c.Endpoint == "" {
    43  			return fmt.Errorf("endpoint should be set for protocol %q", c.Protocol)
    44  		}
    45  	case ProtocolNone, ProtocolStdout:
    46  		if c.Endpoint != "" {
    47  			return errors.New("endpoint should not be set when protocol is 'none'")
    48  		}
    49  	default:
    50  		return fmt.Errorf("unsupported protocol %q", c.Protocol)
    51  	}
    52  
    53  	if c.SamplingRate < 0 {
    54  		return fmt.Errorf("sampling rate %f should be greater or equal to zero", c.SamplingRate)
    55  	} else if c.SamplingRate > 1.0 {
    56  		return fmt.Errorf("sampling rate %f should be less than or equal to one", c.SamplingRate)
    57  	}
    58  	return nil
    59  }
    60  
    61  func DefaultConfig() Config {
    62  	return Config{
    63  		Protocol: ProtocolNone,
    64  	}
    65  }
    66  
    67  func NewFromMap(m map[string]string) (Config, error) {
    68  	return NewFromMapWithPrefix("", m)
    69  }
    70  
    71  func NewFromMapWithPrefix(prefix string, m map[string]string) (Config, error) {
    72  	c := DefaultConfig()
    73  
    74  	err := configmap.Parse(m,
    75  		configmap.As(prefix+"tracing-protocol", &c.Protocol),
    76  		configmap.As(prefix+"tracing-endpoint", &c.Endpoint),
    77  		configmap.As(prefix+"tracing-sampling-rate", &c.SamplingRate),
    78  	)
    79  	if err != nil {
    80  		return c, err
    81  	}
    82  
    83  	return c, c.Validate()
    84  }