knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/observability/runtime/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 runtime
    18  
    19  import (
    20  	"fmt"
    21  	"time"
    22  
    23  	configmap "knative.dev/pkg/configmap/parser"
    24  )
    25  
    26  const (
    27  	ProfilingEnabled  = "enabled"
    28  	ProfilingDisabled = "disabled"
    29  )
    30  
    31  type Config struct {
    32  	Profiling      string        `json:"profiling,omitempty"`
    33  	ExportInterval time.Duration `json:"exportInterval,omitempty"`
    34  }
    35  
    36  func (c *Config) Validate() error {
    37  	switch c.Profiling {
    38  	case ProfilingEnabled, ProfilingDisabled:
    39  	default:
    40  		return fmt.Errorf("unsupported profile setting %q", c.Profiling)
    41  	}
    42  
    43  	// ExportInterval == 0 => OTel will use a default value
    44  	if c.ExportInterval < 0 {
    45  		return fmt.Errorf("export interval %q should be greater than zero", c.ExportInterval)
    46  	}
    47  	return nil
    48  }
    49  
    50  func (c *Config) ProfilingEnabled() bool {
    51  	return c.Profiling == ProfilingEnabled
    52  }
    53  
    54  func DefaultConfig() Config {
    55  	return Config{
    56  		Profiling: ProfilingDisabled,
    57  		// same as OTel runtime.DefaultMinimumReadMemStatsInterval
    58  		ExportInterval: 15 * time.Second,
    59  	}
    60  }
    61  
    62  func NewFromMap(m map[string]string) (Config, error) {
    63  	c := DefaultConfig()
    64  
    65  	err := configmap.Parse(m,
    66  		configmap.As("runtime-profiling", &c.Profiling),
    67  		configmap.As("runtime-export-interval", &c.ExportInterval),
    68  	)
    69  	if err != nil {
    70  		return c, err
    71  	}
    72  
    73  	return c, c.Validate()
    74  }