envvar.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. /*
  2. Copyright 2024 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package features
  14. import (
  15. "fmt"
  16. "os"
  17. "strconv"
  18. "sync"
  19. "sync/atomic"
  20. "k8s.io/apimachinery/pkg/util/naming"
  21. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  22. "k8s.io/klog/v2"
  23. )
  24. // internalPackages are packages that ignored when creating a name for featureGates. These packages are in the common
  25. // call chains, so they'd be unhelpful as names.
  26. var internalPackages = []string{"k8s.io/client-go/features/envvar.go"}
  27. var _ Gates = &envVarFeatureGates{}
  28. // newEnvVarFeatureGates creates a feature gate that allows for registration
  29. // of features and checking if the features are enabled.
  30. //
  31. // On the first call to Enabled, the effective state of all known features is loaded from
  32. // environment variables. The environment variable read for a given feature is formed by
  33. // concatenating the prefix "KUBE_FEATURE_" with the feature's name.
  34. //
  35. // For example, if you have a feature named "MyFeature"
  36. // setting an environmental variable "KUBE_FEATURE_MyFeature"
  37. // will allow you to configure the state of that feature.
  38. //
  39. // Please note that environmental variables can only be set to the boolean value.
  40. // Incorrect values will be ignored and logged.
  41. //
  42. // Features can also be set directly via the Set method.
  43. // In that case, these features take precedence over
  44. // features set via environmental variables.
  45. func newEnvVarFeatureGates(features map[Feature]FeatureSpec) *envVarFeatureGates {
  46. known := map[Feature]FeatureSpec{}
  47. for name, spec := range features {
  48. known[name] = spec
  49. }
  50. fg := &envVarFeatureGates{
  51. callSiteName: naming.GetNameFromCallsite(internalPackages...),
  52. known: known,
  53. }
  54. fg.enabledViaEnvVar.Store(map[Feature]bool{})
  55. fg.enabledViaSetMethod = map[Feature]bool{}
  56. return fg
  57. }
  58. // envVarFeatureGates implements Gates and allows for feature registration.
  59. type envVarFeatureGates struct {
  60. // callSiteName holds the name of the file
  61. // that created this instance
  62. callSiteName string
  63. // readEnvVarsOnce guards reading environmental variables
  64. readEnvVarsOnce sync.Once
  65. // known holds known feature gates
  66. known map[Feature]FeatureSpec
  67. // enabledViaEnvVar holds a map[Feature]bool
  68. // with values explicitly set via env var
  69. enabledViaEnvVar atomic.Value
  70. // lockEnabledViaSetMethod protects enabledViaSetMethod
  71. lockEnabledViaSetMethod sync.RWMutex
  72. // enabledViaSetMethod holds values explicitly set
  73. // via Set method, features stored in this map take
  74. // precedence over features stored in enabledViaEnvVar
  75. enabledViaSetMethod map[Feature]bool
  76. // readEnvVars holds the boolean value which
  77. // indicates whether readEnvVarsOnce has been called.
  78. readEnvVars atomic.Bool
  79. }
  80. // Enabled returns true if the key is enabled. If the key is not known, this call will panic.
  81. func (f *envVarFeatureGates) Enabled(key Feature) bool {
  82. if v, ok := f.wasFeatureEnabledViaSetMethod(key); ok {
  83. // ensue that the state of all known features
  84. // is loaded from environment variables
  85. // on the first call to Enabled method.
  86. if !f.hasAlreadyReadEnvVar() {
  87. _ = f.getEnabledMapFromEnvVar()
  88. }
  89. return v
  90. }
  91. if v, ok := f.getEnabledMapFromEnvVar()[key]; ok {
  92. return v
  93. }
  94. if v, ok := f.known[key]; ok {
  95. return v.Default
  96. }
  97. panic(fmt.Errorf("feature %q is not registered in FeatureGates %q", key, f.callSiteName))
  98. }
  99. // Set sets the given feature to the given value.
  100. //
  101. // Features set via this method take precedence over
  102. // the features set via environment variables.
  103. func (f *envVarFeatureGates) Set(featureName Feature, featureValue bool) error {
  104. feature, ok := f.known[featureName]
  105. if !ok {
  106. return fmt.Errorf("feature %q is not registered in FeatureGates %q", featureName, f.callSiteName)
  107. }
  108. if feature.LockToDefault && feature.Default != featureValue {
  109. return fmt.Errorf("cannot set feature gate %q to %v, feature is locked to %v", featureName, featureValue, feature.Default)
  110. }
  111. f.lockEnabledViaSetMethod.Lock()
  112. defer f.lockEnabledViaSetMethod.Unlock()
  113. f.enabledViaSetMethod[featureName] = featureValue
  114. return nil
  115. }
  116. // getEnabledMapFromEnvVar will fill the enabled map on the first call.
  117. // This is the only time a known feature can be set to a value
  118. // read from the corresponding environmental variable.
  119. func (f *envVarFeatureGates) getEnabledMapFromEnvVar() map[Feature]bool {
  120. f.readEnvVarsOnce.Do(func() {
  121. featureGatesState := map[Feature]bool{}
  122. for feature, featureSpec := range f.known {
  123. featureState, featureStateSet := os.LookupEnv(fmt.Sprintf("KUBE_FEATURE_%s", feature))
  124. if !featureStateSet {
  125. continue
  126. }
  127. boolVal, boolErr := strconv.ParseBool(featureState)
  128. switch {
  129. case boolErr != nil:
  130. utilruntime.HandleError(fmt.Errorf("cannot set feature gate %q to %q, due to %v", feature, featureState, boolErr))
  131. case featureSpec.LockToDefault:
  132. if boolVal != featureSpec.Default {
  133. utilruntime.HandleError(fmt.Errorf("cannot set feature gate %q to %q, feature is locked to %v", feature, featureState, featureSpec.Default))
  134. break
  135. }
  136. featureGatesState[feature] = featureSpec.Default
  137. default:
  138. featureGatesState[feature] = boolVal
  139. }
  140. }
  141. f.enabledViaEnvVar.Store(featureGatesState)
  142. f.readEnvVars.Store(true)
  143. for feature, featureSpec := range f.known {
  144. if featureState, ok := featureGatesState[feature]; ok {
  145. klog.V(1).InfoS("Feature gate updated state", "feature", feature, "enabled", featureState)
  146. continue
  147. }
  148. klog.V(1).InfoS("Feature gate default state", "feature", feature, "enabled", featureSpec.Default)
  149. }
  150. })
  151. return f.enabledViaEnvVar.Load().(map[Feature]bool)
  152. }
  153. func (f *envVarFeatureGates) wasFeatureEnabledViaSetMethod(key Feature) (bool, bool) {
  154. f.lockEnabledViaSetMethod.RLock()
  155. defer f.lockEnabledViaSetMethod.RUnlock()
  156. value, found := f.enabledViaSetMethod[key]
  157. return value, found
  158. }
  159. func (f *envVarFeatureGates) hasAlreadyReadEnvVar() bool {
  160. return f.readEnvVars.Load()
  161. }