...

Source file src/k8s.io/client-go/features/envvar.go

Documentation: k8s.io/client-go/features

     1  /*
     2  Copyright 2024 The Kubernetes 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 features
    18  
    19  import (
    20  	"fmt"
    21  	"os"
    22  	"strconv"
    23  	"sync"
    24  	"sync/atomic"
    25  
    26  	"k8s.io/apimachinery/pkg/util/naming"
    27  	utilruntime "k8s.io/apimachinery/pkg/util/runtime"
    28  	"k8s.io/klog/v2"
    29  )
    30  
    31  // internalPackages are packages that ignored when creating a name for featureGates. These packages are in the common
    32  // call chains, so they'd be unhelpful as names.
    33  var internalPackages = []string{"k8s.io/client-go/features/envvar.go"}
    34  
    35  var _ Gates = &envVarFeatureGates{}
    36  
    37  // newEnvVarFeatureGates creates a feature gate that allows for registration
    38  // of features and checking if the features are enabled.
    39  //
    40  // On the first call to Enabled, the effective state of all known features is loaded from
    41  // environment variables. The environment variable read for a given feature is formed by
    42  // concatenating the prefix "KUBE_FEATURE_" with the feature's name.
    43  //
    44  // For example, if you have a feature named "MyFeature"
    45  // setting an environmental variable "KUBE_FEATURE_MyFeature"
    46  // will allow you to configure the state of that feature.
    47  //
    48  // Please note that environmental variables can only be set to the boolean value.
    49  // Incorrect values will be ignored and logged.
    50  func newEnvVarFeatureGates(features map[Feature]FeatureSpec) *envVarFeatureGates {
    51  	known := map[Feature]FeatureSpec{}
    52  	for name, spec := range features {
    53  		known[name] = spec
    54  	}
    55  
    56  	fg := &envVarFeatureGates{
    57  		callSiteName: naming.GetNameFromCallsite(internalPackages...),
    58  		known:        known,
    59  	}
    60  	fg.enabled.Store(map[Feature]bool{})
    61  
    62  	return fg
    63  }
    64  
    65  // envVarFeatureGates implements Gates and allows for feature registration.
    66  type envVarFeatureGates struct {
    67  	// callSiteName holds the name of the file
    68  	// that created this instance
    69  	callSiteName string
    70  
    71  	// readEnvVarsOnce guards reading environmental variables
    72  	readEnvVarsOnce sync.Once
    73  
    74  	// known holds known feature gates
    75  	known map[Feature]FeatureSpec
    76  
    77  	// enabled holds a map[Feature]bool
    78  	// with values explicitly set via env var
    79  	enabled atomic.Value
    80  
    81  	// readEnvVars holds the boolean value which
    82  	// indicates whether readEnvVarsOnce has been called.
    83  	readEnvVars atomic.Bool
    84  }
    85  
    86  // Enabled returns true if the key is enabled.  If the key is not known, this call will panic.
    87  func (f *envVarFeatureGates) Enabled(key Feature) bool {
    88  	if v, ok := f.getEnabledMapFromEnvVar()[key]; ok {
    89  		return v
    90  	}
    91  	if v, ok := f.known[key]; ok {
    92  		return v.Default
    93  	}
    94  	panic(fmt.Errorf("feature %q is not registered in FeatureGates %q", key, f.callSiteName))
    95  }
    96  
    97  // getEnabledMapFromEnvVar will fill the enabled map on the first call.
    98  // This is the only time a known feature can be set to a value
    99  // read from the corresponding environmental variable.
   100  func (f *envVarFeatureGates) getEnabledMapFromEnvVar() map[Feature]bool {
   101  	f.readEnvVarsOnce.Do(func() {
   102  		featureGatesState := map[Feature]bool{}
   103  		for feature, featureSpec := range f.known {
   104  			featureState, featureStateSet := os.LookupEnv(fmt.Sprintf("KUBE_FEATURE_%s", feature))
   105  			if !featureStateSet {
   106  				continue
   107  			}
   108  			boolVal, boolErr := strconv.ParseBool(featureState)
   109  			switch {
   110  			case boolErr != nil:
   111  				utilruntime.HandleError(fmt.Errorf("cannot set feature gate %q to %q, due to %v", feature, featureState, boolErr))
   112  			case featureSpec.LockToDefault:
   113  				if boolVal != featureSpec.Default {
   114  					utilruntime.HandleError(fmt.Errorf("cannot set feature gate %q to %q, feature is locked to %v", feature, featureState, featureSpec.Default))
   115  					break
   116  				}
   117  				featureGatesState[feature] = featureSpec.Default
   118  			default:
   119  				featureGatesState[feature] = boolVal
   120  			}
   121  		}
   122  		f.enabled.Store(featureGatesState)
   123  		f.readEnvVars.Store(true)
   124  
   125  		for feature, featureSpec := range f.known {
   126  			if featureState, ok := featureGatesState[feature]; ok {
   127  				klog.V(1).InfoS("Feature gate updated state", "feature", feature, "enabled", featureState)
   128  				continue
   129  			}
   130  			klog.V(1).InfoS("Feature gate default state", "feature", feature, "enabled", featureSpec.Default)
   131  		}
   132  	})
   133  	return f.enabled.Load().(map[Feature]bool)
   134  }
   135  
   136  func (f *envVarFeatureGates) hasAlreadyReadEnvVar() bool {
   137  	return f.readEnvVars.Load()
   138  }
   139  

View as plain text