...

Source file src/k8s.io/kubernetes/pkg/kubelet/apis/config/helpers_test.go

Documentation: k8s.io/kubernetes/pkg/kubelet/apis/config

     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  		"PodLogsDir",
   160  	)
   161  
   162  	// KubeletConfiguration fields that do not contain file paths.
   163  	kubeletConfigurationNonPathFieldPaths = sets.NewString(
   164  		"Address",
   165  		"AllowedUnsafeSysctls[*]",
   166  		"Authentication.Anonymous.Enabled",
   167  		"Authentication.Webhook.CacheTTL.Duration",
   168  		"Authentication.Webhook.Enabled",
   169  		"Authorization.Mode",
   170  		"Authorization.Webhook.CacheAuthorizedTTL.Duration",
   171  		"Authorization.Webhook.CacheUnauthorizedTTL.Duration",
   172  		"CPUCFSQuota",
   173  		"CPUCFSQuotaPeriod.Duration",
   174  		"CPUManagerPolicy",
   175  		"CPUManagerPolicyOptions[*]",
   176  		"CPUManagerReconcilePeriod.Duration",
   177  		"TopologyManagerPolicy",
   178  		"TopologyManagerScope",
   179  		"TopologyManagerPolicyOptions[*]",
   180  		"QOSReserved[*]",
   181  		"CgroupDriver",
   182  		"CgroupRoot",
   183  		"CgroupsPerQOS",
   184  		"ClusterDNS[*]",
   185  		"ClusterDomain",
   186  		"ConfigMapAndSecretChangeDetectionStrategy",
   187  		"ContainerLogMaxFiles",
   188  		"ContainerLogMaxSize",
   189  		"ContainerLogMaxWorkers",
   190  		"ContainerLogMonitorInterval",
   191  		"ContentType",
   192  		"EnableContentionProfiling",
   193  		"EnableControllerAttachDetach",
   194  		"EnableDebugFlagsHandler",
   195  		"EnableDebuggingHandlers",
   196  		"EnableSystemLogQuery",
   197  		"EnableProfilingHandler",
   198  		"EnableServer",
   199  		"EnableSystemLogHandler",
   200  		"EnforceNodeAllocatable[*]",
   201  		"EventBurst",
   202  		"EventRecordQPS",
   203  		"EvictionHard[*]",
   204  		"EvictionMaxPodGracePeriod",
   205  		"EvictionMinimumReclaim[*]",
   206  		"EvictionPressureTransitionPeriod.Duration",
   207  		"EvictionSoft[*]",
   208  		"EvictionSoftGracePeriod[*]",
   209  		"FailSwapOn",
   210  		"FeatureGates[*]",
   211  		"FileCheckFrequency.Duration",
   212  		"HTTPCheckFrequency.Duration",
   213  		"HairpinMode",
   214  		"HealthzBindAddress",
   215  		"HealthzPort",
   216  		"Logging.FlushFrequency",
   217  		"Logging.Format",
   218  		"Logging.Options.JSON.OutputRoutingOptions.InfoBufferSize.Quantity.Format",
   219  		"Logging.Options.JSON.OutputRoutingOptions.InfoBufferSize.Quantity.d.Dec.scale",
   220  		"Logging.Options.JSON.OutputRoutingOptions.InfoBufferSize.Quantity.d.Dec.unscaled.abs[*]",
   221  		"Logging.Options.JSON.OutputRoutingOptions.InfoBufferSize.Quantity.d.Dec.unscaled.neg",
   222  		"Logging.Options.JSON.OutputRoutingOptions.InfoBufferSize.Quantity.i.scale",
   223  		"Logging.Options.JSON.OutputRoutingOptions.InfoBufferSize.Quantity.i.value",
   224  		"Logging.Options.JSON.OutputRoutingOptions.InfoBufferSize.Quantity.s",
   225  		"Logging.Options.JSON.OutputRoutingOptions.SplitStream",
   226  		"Logging.Options.Text.OutputRoutingOptions.InfoBufferSize.Quantity.Format",
   227  		"Logging.Options.Text.OutputRoutingOptions.InfoBufferSize.Quantity.d.Dec.scale",
   228  		"Logging.Options.Text.OutputRoutingOptions.InfoBufferSize.Quantity.d.Dec.unscaled.abs[*]",
   229  		"Logging.Options.Text.OutputRoutingOptions.InfoBufferSize.Quantity.d.Dec.unscaled.neg",
   230  		"Logging.Options.Text.OutputRoutingOptions.InfoBufferSize.Quantity.i.scale",
   231  		"Logging.Options.Text.OutputRoutingOptions.InfoBufferSize.Quantity.i.value",
   232  		"Logging.Options.Text.OutputRoutingOptions.InfoBufferSize.Quantity.s",
   233  		"Logging.Options.Text.OutputRoutingOptions.SplitStream",
   234  		"Logging.VModule[*].FilePattern",
   235  		"Logging.VModule[*].Verbosity",
   236  		"Logging.Verbosity",
   237  		"TLSCipherSuites[*]",
   238  		"TLSMinVersion",
   239  		"IPTablesDropBit",
   240  		"IPTablesMasqueradeBit",
   241  		"ImageGCHighThresholdPercent",
   242  		"ImageGCLowThresholdPercent",
   243  		"ImageMinimumGCAge.Duration",
   244  		"ImageMaximumGCAge.Duration",
   245  		"KernelMemcgNotification",
   246  		"KubeAPIBurst",
   247  		"KubeAPIQPS",
   248  		"KubeReservedCgroup",
   249  		"KubeReserved[*]",
   250  		"KubeletCgroups",
   251  		"MakeIPTablesUtilChains",
   252  		"RotateCertificates",
   253  		"ServerTLSBootstrap",
   254  		"StaticPodURL",
   255  		"StaticPodURLHeader[*][*]",
   256  		"MaxOpenFiles",
   257  		"MaxPods",
   258  		"MemoryManagerPolicy",
   259  		"MemorySwap.SwapBehavior",
   260  		"NodeLeaseDurationSeconds",
   261  		"NodeStatusMaxImages",
   262  		"NodeStatusUpdateFrequency.Duration",
   263  		"NodeStatusReportFrequency.Duration",
   264  		"OOMScoreAdj",
   265  		"PodCIDR",
   266  		"PodPidsLimit",
   267  		"PodsPerCore",
   268  		"Port",
   269  		"ProtectKernelDefaults",
   270  		"ProviderID",
   271  		"ReadOnlyPort",
   272  		"RegisterNode",
   273  		"RegistryBurst",
   274  		"RegistryPullQPS",
   275  		"ReservedMemory",
   276  		"ReservedSystemCPUs",
   277  		"RegisterWithTaints",
   278  		"RuntimeRequestTimeout.Duration",
   279  		"RunOnce",
   280  		"SeccompDefault",
   281  		"SerializeImagePulls",
   282  		"MaxParallelImagePulls",
   283  		"ShowHiddenMetricsForVersion",
   284  		"ShutdownGracePeriodByPodPriority[*].Priority",
   285  		"ShutdownGracePeriodByPodPriority[*].ShutdownGracePeriodSeconds",
   286  		"StreamingConnectionIdleTimeout.Duration",
   287  		"SyncFrequency.Duration",
   288  		"SystemCgroups",
   289  		"SystemReservedCgroup",
   290  		"SystemReserved[*]",
   291  		"TypeMeta.APIVersion",
   292  		"TypeMeta.Kind",
   293  		"VolumeStatsAggPeriod.Duration",
   294  		"VolumePluginDir",
   295  		"ShutdownGracePeriod.Duration",
   296  		"ShutdownGracePeriodCriticalPods.Duration",
   297  		"MemoryThrottlingFactor",
   298  		"ContainerRuntimeEndpoint",
   299  		"ImageServiceEndpoint",
   300  		"Tracing.Endpoint",
   301  		"Tracing.SamplingRatePerMillion",
   302  		"LocalStorageCapacityIsolation",
   303  	)
   304  )
   305  

View as plain text