k8s.io/kubernetes@v1.29.3/pkg/kubelet/apis/config/helpers_test.go (about) 1 /* 2 Copyright 2017 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 config 18 19 import ( 20 "reflect" 21 "strings" 22 "testing" 23 24 "k8s.io/apimachinery/pkg/util/sets" 25 "k8s.io/apimachinery/pkg/util/validation/field" 26 ) 27 28 func TestKubeletConfigurationPathFields(t *testing.T) { 29 // ensure the intersection of kubeletConfigurationPathFieldPaths and KubeletConfigurationNonPathFields is empty 30 if i := kubeletConfigurationPathFieldPaths.Intersection(kubeletConfigurationNonPathFieldPaths); len(i) > 0 { 31 t.Fatalf("expect the intersection of kubeletConfigurationPathFieldPaths and "+ 32 "KubeletConfigurationNonPathFields to be empty, got:\n%s", 33 strings.Join(i.List(), "\n")) 34 } 35 36 // ensure that kubeletConfigurationPathFields U kubeletConfigurationNonPathFields == allPrimitiveFieldPaths(KubeletConfiguration) 37 expect := sets.NewString().Union(kubeletConfigurationPathFieldPaths).Union(kubeletConfigurationNonPathFieldPaths) 38 result := allPrimitiveFieldPaths(t, expect, reflect.TypeOf(&KubeletConfiguration{}), nil) 39 if !expect.Equal(result) { 40 // expected fields missing from result 41 missing := expect.Difference(result) 42 // unexpected fields in result but not specified in expect 43 unexpected := result.Difference(expect) 44 if len(missing) > 0 { 45 t.Errorf("the following fields were expected, but missing from the result. "+ 46 "If the field has been removed, please remove it from the kubeletConfigurationPathFieldPaths set "+ 47 "and the KubeletConfigurationPathRefs function, "+ 48 "or remove it from the kubeletConfigurationNonPathFieldPaths set, as appropriate:\n%s", 49 strings.Join(missing.List(), "\n")) 50 } 51 if len(unexpected) > 0 { 52 t.Errorf("the following fields were in the result, but unexpected. "+ 53 "If the field is new, please add it to the kubeletConfigurationPathFieldPaths set "+ 54 "and the KubeletConfigurationPathRefs function, "+ 55 "or add it to the kubeletConfigurationNonPathFieldPaths set, as appropriate:\n%s", 56 strings.Join(unexpected.List(), "\n")) 57 } 58 } 59 } 60 61 // allPrimitiveFieldPaths returns the set of field paths in type `tp`, rooted at `path`. 62 // It recursively descends into the definition of type `tp` accumulating paths to primitive leaf fields or paths in `skipRecurseList`. 63 func allPrimitiveFieldPaths(t *testing.T, skipRecurseList sets.String, tp reflect.Type, path *field.Path) sets.String { 64 // if the current field path is in the list of paths we should not recurse into, 65 // return here rather than descending and accumulating child field paths 66 if pathStr := path.String(); len(pathStr) > 0 && skipRecurseList.Has(pathStr) { 67 return sets.NewString(pathStr) 68 } 69 70 paths := sets.NewString() 71 switch tp.Kind() { 72 case reflect.Pointer: 73 paths.Insert(allPrimitiveFieldPaths(t, skipRecurseList, tp.Elem(), path).List()...) 74 case reflect.Struct: 75 for i := 0; i < tp.NumField(); i++ { 76 field := tp.Field(i) 77 paths.Insert(allPrimitiveFieldPaths(t, skipRecurseList, field.Type, path.Child(field.Name)).List()...) 78 } 79 case reflect.Map, reflect.Slice: 80 paths.Insert(allPrimitiveFieldPaths(t, skipRecurseList, tp.Elem(), path.Key("*")).List()...) 81 case reflect.Interface: 82 t.Fatalf("unexpected interface{} field %s", path.String()) 83 default: 84 // if we hit a primitive type, we're at a leaf 85 paths.Insert(path.String()) 86 } 87 return paths 88 } 89 90 //lint:file-ignore U1000 Ignore dummy types, used by tests. 91 92 // dummy helper types 93 type foo struct { 94 foo int 95 } 96 type bar struct { 97 str string 98 strptr *string 99 100 ints []int 101 stringMap map[string]string 102 103 foo foo 104 fooptr *foo 105 106 bars []foo 107 barMap map[string]foo 108 109 skipRecurseStruct foo 110 skipRecursePointer *foo 111 skipRecurseList1 []foo 112 skipRecurseList2 []foo 113 skipRecurseMap1 map[string]foo 114 skipRecurseMap2 map[string]foo 115 } 116 117 func TestAllPrimitiveFieldPaths(t *testing.T) { 118 expect := sets.NewString( 119 "str", 120 "strptr", 121 "ints[*]", 122 "stringMap[*]", 123 "foo.foo", 124 "fooptr.foo", 125 "bars[*].foo", 126 "barMap[*].foo", 127 "skipRecurseStruct", // skip recursing a struct 128 "skipRecursePointer", // skip recursing a struct pointer 129 "skipRecurseList1", // skip recursing a list 130 "skipRecurseList2[*]", // skip recursing list items 131 "skipRecurseMap1", // skip recursing a map 132 "skipRecurseMap2[*]", // skip recursing map items 133 ) 134 result := allPrimitiveFieldPaths(t, expect, reflect.TypeOf(&bar{}), nil) 135 if !expect.Equal(result) { 136 // expected fields missing from result 137 missing := expect.Difference(result) 138 139 // unexpected fields in result but not specified in expect 140 unexpected := result.Difference(expect) 141 142 if len(missing) > 0 { 143 t.Errorf("the following fields were expected, but missing from the result:\n%s", strings.Join(missing.List(), "\n")) 144 } 145 if len(unexpected) > 0 { 146 t.Errorf("the following fields were in the result, but unexpected:\n%s", strings.Join(unexpected.List(), "\n")) 147 } 148 } 149 } 150 151 var ( 152 // KubeletConfiguration fields that contain file paths. If you update this, also update KubeletConfigurationPathRefs! 153 kubeletConfigurationPathFieldPaths = sets.NewString( 154 "StaticPodPath", 155 "Authentication.X509.ClientCAFile", 156 "TLSCertFile", 157 "TLSPrivateKeyFile", 158 "ResolverConfig", 159 ) 160 161 // KubeletConfiguration fields that do not contain file paths. 162 kubeletConfigurationNonPathFieldPaths = sets.NewString( 163 "Address", 164 "AllowedUnsafeSysctls[*]", 165 "Authentication.Anonymous.Enabled", 166 "Authentication.Webhook.CacheTTL.Duration", 167 "Authentication.Webhook.Enabled", 168 "Authorization.Mode", 169 "Authorization.Webhook.CacheAuthorizedTTL.Duration", 170 "Authorization.Webhook.CacheUnauthorizedTTL.Duration", 171 "CPUCFSQuota", 172 "CPUCFSQuotaPeriod.Duration", 173 "CPUManagerPolicy", 174 "CPUManagerPolicyOptions[*]", 175 "CPUManagerReconcilePeriod.Duration", 176 "TopologyManagerPolicy", 177 "TopologyManagerScope", 178 "TopologyManagerPolicyOptions[*]", 179 "QOSReserved[*]", 180 "CgroupDriver", 181 "CgroupRoot", 182 "CgroupsPerQOS", 183 "ClusterDNS[*]", 184 "ClusterDomain", 185 "ConfigMapAndSecretChangeDetectionStrategy", 186 "ContainerLogMaxFiles", 187 "ContainerLogMaxSize", 188 "ContentType", 189 "EnableContentionProfiling", 190 "EnableControllerAttachDetach", 191 "EnableDebugFlagsHandler", 192 "EnableDebuggingHandlers", 193 "EnableSystemLogQuery", 194 "EnableProfilingHandler", 195 "EnableServer", 196 "EnableSystemLogHandler", 197 "EnforceNodeAllocatable[*]", 198 "EventBurst", 199 "EventRecordQPS", 200 "EvictionHard[*]", 201 "EvictionMaxPodGracePeriod", 202 "EvictionMinimumReclaim[*]", 203 "EvictionPressureTransitionPeriod.Duration", 204 "EvictionSoft[*]", 205 "EvictionSoftGracePeriod[*]", 206 "FailSwapOn", 207 "FeatureGates[*]", 208 "FileCheckFrequency.Duration", 209 "HTTPCheckFrequency.Duration", 210 "HairpinMode", 211 "HealthzBindAddress", 212 "HealthzPort", 213 "Logging.FlushFrequency", 214 "Logging.Format", 215 "Logging.Options.JSON.InfoBufferSize.Quantity.Format", 216 "Logging.Options.JSON.InfoBufferSize.Quantity.d.Dec.scale", 217 "Logging.Options.JSON.InfoBufferSize.Quantity.d.Dec.unscaled.abs[*]", 218 "Logging.Options.JSON.InfoBufferSize.Quantity.d.Dec.unscaled.neg", 219 "Logging.Options.JSON.InfoBufferSize.Quantity.i.scale", 220 "Logging.Options.JSON.InfoBufferSize.Quantity.i.value", 221 "Logging.Options.JSON.InfoBufferSize.Quantity.s", 222 "Logging.Options.JSON.SplitStream", 223 "Logging.VModule[*].FilePattern", 224 "Logging.VModule[*].Verbosity", 225 "Logging.Verbosity", 226 "TLSCipherSuites[*]", 227 "TLSMinVersion", 228 "IPTablesDropBit", 229 "IPTablesMasqueradeBit", 230 "ImageGCHighThresholdPercent", 231 "ImageGCLowThresholdPercent", 232 "ImageMinimumGCAge.Duration", 233 "ImageMaximumGCAge.Duration", 234 "KernelMemcgNotification", 235 "KubeAPIBurst", 236 "KubeAPIQPS", 237 "KubeReservedCgroup", 238 "KubeReserved[*]", 239 "KubeletCgroups", 240 "MakeIPTablesUtilChains", 241 "RotateCertificates", 242 "ServerTLSBootstrap", 243 "StaticPodURL", 244 "StaticPodURLHeader[*][*]", 245 "MaxOpenFiles", 246 "MaxPods", 247 "MemoryManagerPolicy", 248 "MemorySwap.SwapBehavior", 249 "NodeLeaseDurationSeconds", 250 "NodeStatusMaxImages", 251 "NodeStatusUpdateFrequency.Duration", 252 "NodeStatusReportFrequency.Duration", 253 "OOMScoreAdj", 254 "PodCIDR", 255 "PodPidsLimit", 256 "PodsPerCore", 257 "Port", 258 "ProtectKernelDefaults", 259 "ProviderID", 260 "ReadOnlyPort", 261 "RegisterNode", 262 "RegistryBurst", 263 "RegistryPullQPS", 264 "ReservedMemory", 265 "ReservedSystemCPUs", 266 "RegisterWithTaints", 267 "RuntimeRequestTimeout.Duration", 268 "RunOnce", 269 "SeccompDefault", 270 "SerializeImagePulls", 271 "MaxParallelImagePulls", 272 "ShowHiddenMetricsForVersion", 273 "ShutdownGracePeriodByPodPriority[*].Priority", 274 "ShutdownGracePeriodByPodPriority[*].ShutdownGracePeriodSeconds", 275 "StreamingConnectionIdleTimeout.Duration", 276 "SyncFrequency.Duration", 277 "SystemCgroups", 278 "SystemReservedCgroup", 279 "SystemReserved[*]", 280 "TypeMeta.APIVersion", 281 "TypeMeta.Kind", 282 "VolumeStatsAggPeriod.Duration", 283 "VolumePluginDir", 284 "ShutdownGracePeriod.Duration", 285 "ShutdownGracePeriodCriticalPods.Duration", 286 "MemoryThrottlingFactor", 287 "ContainerRuntimeEndpoint", 288 "ImageServiceEndpoint", 289 "Tracing.Endpoint", 290 "Tracing.SamplingRatePerMillion", 291 "LocalStorageCapacityIsolation", 292 ) 293 )