// returned. func (adapter *EndpointsAdapter) Create(namespace string, endpoints *corev1.Endpoints) (*corev1.Endpoints, error) { endpoints, err := adapter.endpointClient.Endpoints(namespace).Create(endpoints) <del> if err == nil && adapter.endpointSliceClient != nil { _, err = adapter.ensureEndpointSliceFromEndpoints(namespace, endpoints) </del> <ins> if err == nil { err = adapter.EnsureEndpointSliceFromEndpoints(namespace, endpoints) </ins> } return endpoints, err }


} func (f *FakeMounter) IsNotMountPoint(dir string) (bool, error) { <del> return IsNotMountPoint(f, dir) </del> <ins> return isNotMountPoint(f, dir) </ins> } func (f *FakeMounter) IsLikelyNotMountPoint(file string) (bool, error) {


CLUSTER_IP_RANGE="${CONTAINER_SUBNET}" fi <ins> # If enabled kube-controller-manager will be started with the --enable-hostpath-provisioner flag ENABLE_HOSTPATH_PROVISIONER="${ENABLE_HOSTPATH_PROVISIONER:-true}" </ins> # OpenContrail networking plugin specific settings OPENCONTRAIL_TAG="${OPENCONTRAIL_TAG:-R2.20}" OPENCONTRAIL_KUBERNETES_TAG="${OPENCONTRAIL_KUBERNETES_TAG:-master}"


}, }, }, <del> }) </del> <ins> }, true) </ins> }) // The following tests for remote command execution and port forwarding are


importmap = "k8s.io/kubernetes/vendor/k8s.io/apiserver/pkg/server/healthz", importpath = "k8s.io/apiserver/pkg/server/healthz", deps = [ <ins> "//staging/src/k8s.io/apimachinery/pkg/util/sets:go_default_library", </ins> "//staging/src/k8s.io/apimachinery/pkg/util/wait:go_default_library", "//vendor/k8s.io/klog:go_default_library", ],


} } } <ins> func TestPredicatesRegistered(t *testing.T) { var functionNames []string // Files and directories which predicates may be referenced targetFiles := []string{ "./../../algorithmprovider/defaults/defaults.go", // Default algorithm "./../../factory/plugins.go",                     // Registered in init() "./../../../../../pkg/",                          // kubernetes/pkg, often used by kubelet or controller } // List all golang source files under ./predicates/, excluding test files and sub-directories. files, err := codeinspector.GetSourceCodeFiles(".") if err != nil { t.Errorf("unexpected error: %v when listing files in current directory", err) } // Get all public predicates in files. for _, filePath := range files { functions, err := codeinspector.GetPublicFunctions(filePath) if err == nil { functionNames = append(functionNames, functions...) } else { t.Errorf("unexpected error when parsing %s", filePath) } } // Check if all public predicates are referenced in target files. for _, functionName := range functionNames { args := []string{"-rl", functionName} args = append(args, targetFiles...) err := exec.Command("grep", args...).Run() if err != nil { switch err.Error() { case "exit status 2": t.Errorf("unexpected error when checking %s", functionName) case "exit status 1": t.Errorf("predicate %s is implemented as public but seems not registered or used in any other place", functionName) } } } } </ins>


if [ ! -w $(dirname `which gcloud`) ]; then sudo_prefix="sudo" fi <del> ${sudo_prefix} gcloud ${gcloud_prompt:-} components update alpha || true ${sudo_prefix} gcloud ${gcloud_prompt:-} components update beta || true ${sudo_prefix} gcloud ${gcloud_prompt:-} components update ${CMD_GROUP:-} || true ${sudo_prefix} gcloud ${gcloud_prompt:-} components update kubectl|| true </del> <ins> ${sudo_prefix} gcloud ${gcloud_prompt:-} components install alpha || true ${sudo_prefix} gcloud ${gcloud_prompt:-} components install beta || true ${sudo_prefix} gcloud ${gcloud_prompt:-} components install kubectl|| true </ins> ${sudo_prefix} gcloud ${gcloud_prompt:-} components update || true }


// Initialize passes a Kubernetes clientBuilder interface to the cloud provider func (vs *VSphere) Initialize(clientBuilder cloudprovider.ControllerClientBuilder, stop <-chan struct{}) { vs.kubeClient = clientBuilder.ClientOrDie("vsphere-legacy-cloud-provider") <ins> vs.nodeManager.SetNodeGetter(vs.kubeClient.CoreV1()) </ins> } // Initialize Node Informers


return allErrs } <ins> func ValidateNoNewFinalizers(newFinalizers []string, oldFinalizers []string, fldPath *field.Path) field.ErrorList { const newFinalizersErrorMsg string = `no new finalizers can be added if the object is being deleted` allErrs := field.ErrorList{} extra := sets.NewString(newFinalizers...).Difference(sets.NewString(oldFinalizers...)) if len(extra) != 0 { allErrs = append(allErrs, field.Forbidden(fldPath, fmt.Sprintf("no new finalizers can be added if the object is being deleted, found new finalizers %#v", extra.List()))) } return allErrs } </ins> func validateVolumes(volumes []api.Volume, fldPath *field.Path) (sets.String, field.ErrorList) { allErrs := field.ErrorList{}


Fail(fmt.Sprintf(format, a...), 1) } <ins> func providerIs(providers ...string) bool { if testContext.Provider == "" { Fail("testContext.Provider is not defined") } for _, provider := range providers { if strings.ToLower(provider) == strings.ToLower(testContext.Provider) { return true } } return false } </ins> type podCondition func(pod *api.Pod) (bool, error) func waitForPodCondition(c *client.Client, ns, podName, desc string, condition podCondition) error {


} } <del> var reinvocationMarkerFixture = &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Namespace: "default", Name:      "marker", }, Spec: corev1.PodSpec{ Containers: []v1.Container{{ Name:  "fake-name", Image: "fakeimage", }}, }, </del> <ins> func newReinvocationMarkerFixture(namespace string) *corev1.Pod { return &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, Name:      "marker", Labels: map[string]string{ "marker": "true", }, }, Spec: corev1.PodSpec{ Containers: []v1.Container{{ Name:  "fake-name", Image: "fakeimage", }}, }, } </ins> }


InitContainers: []v1.Container{ { Image: image.GetE2EImage(), <del> Name:  podName, </del> <ins> Name:  "init-container", </ins> Command: []string{ "powershell.exe", "-Command",


MUST succeed. It MUST succeed when deleting the Deployment. release: v1.20 file: test/e2e/apps/deployment.go <ins> - testname: Deployment, status sub-resource codename: '[sig-apps] Deployment should validate Deployment Status endpoints [Conformance]' description: When a Deployment is created it MUST succeed. Attempt to read, update and patch its status sub-resource; all mutating sub-resource operations MUST be visible to subsequent reads. release: v1.22 file: test/e2e/apps/deployment.go </ins> - testname: 'PodDisruptionBudget: list and delete collection' codename: '[sig-apps] DisruptionController Listing PodDisruptionBudgets for all namespaces should list and delete a collection of PodDisruptionBudgets [Conformance]'


rc=1 fi <ins> # ensure all generic features are added in alphabetic order lines=$(git grep 'genericfeatures[.].*:' -- pkg/features/kube_features.go) sorted_lines=$(echo "$lines" | sort -f) if [[ "$lines" != "$sorted_lines" ]]; then echo "Generic features in pkg/features/kube_features.go not sorted" >&2 echo >&2 echo "Expected:" >&2 echo "$sorted_lines" >&2 echo >&2 echo "Got:" >&2 echo "$lines" >&2 rc=1 fi </ins> exit $rc


mu.Unlock() } <ins> if !concreteOp.SkipWaitToCompletion { // SkipWaitToCompletion=false indicates this step has waited for the Pods to be scheduled. // So we reset the metrics in global registry; otherwise metrics gathered in this step // will be carried over to next step. legacyregistry.Reset() } </ins> case *churnOp: var namespace string if concreteOp.Namespace != nil {


} func (az *Cloud) getIPForMachine(nodeName types.NodeName) (string, error) { <ins> az.operationPollRateLimiter.Accept() </ins> machine, exists, err := az.getVirtualMachine(nodeName) if !exists { return "", cloudprovider.InstanceNotFound


cmd.Flags().DurationVar(&o.drainer.Timeout, "timeout", o.drainer.Timeout, "The length of time to wait before giving up, zero means infinite") cmd.Flags().StringVarP(&o.drainer.Selector, "selector", "l", o.drainer.Selector, "Selector (label query) to filter on") cmd.Flags().StringVarP(&o.drainer.PodSelector, "pod-selector", "", o.drainer.PodSelector, "Label selector to filter pods on the node") <ins> cmd.Flags().BoolVar(&o.drainer.DisableEviction, "disable-eviction", o.drainer.DisableEviction, "Force drain to use delete, even if eviction is supported. This will bypass checking PodDisruptionBudgets, use with caution.") </ins> cmdutil.AddDryRunFlag(cmd) return cmd


measurePods: 1000 - name: SchedulingMigratedInTreePVs <del> featureGates: CSIMigrationAWS: true </del> workloadTemplate: - opcode: createNodes countParam: $initNodes


import ( goflag "flag" <del> "fmt" </del> "math/rand" "os" "time"


//CredentialsManager credentialManager *SecretCredentialManager <ins> nodeLister corelisters.NodeLister nodeGetter coreclients.NodesGetter </ins> // Mutexes registeredNodesLock   sync.RWMutex nodeInfoLock          sync.RWMutex


klog.Errorf("cannot convert to *v1.Pod: %v", t) return } <ins> klog.V(3).Infof("delete event for scheduled pod %s/%s ", pod.Namespace, pod.Name) </ins> // NOTE: Updates must be written to scheduler cache before invalidating // equivalence cache, because we could snapshot equivalence cache after the // invalidation and then snapshot the cache itself. If the cache is


<ins> /* Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cloudcfg import ( "bytes" "encoding/json" "reflect" "testing" "gopkg.in/v1/yaml" ) func TestYAMLPrinterPrint(t *testing.T) { type testStruct struct { Key        string         `yaml:"Key" json:"Key"` Map        map[string]int `yaml:"Map" json:"Map"` StringList []string       `yaml:"StringList" json:"StringList"` IntList    []int          `yaml:"IntList" json:"IntList"` } testData := testStruct{ "testValue", map[string]int{"TestSubkey": 1}, []string{"a", "b", "c"}, []int{1, 2, 3}, } printer := &YAMLPrinter{} buf := bytes.NewBuffer([]byte{}) err := printer.Print([]byte("invalidJSON"), buf) if err == nil { t.Error("Error: didn't fail on invalid JSON data") } jTestData, err := json.Marshal(&testData) if err != nil { t.Fatal("Unexpected error: couldn't marshal test data") } err = printer.Print(jTestData, buf) if err != nil { t.Fatal(err) } var poutput testStruct err = yaml.Unmarshal(buf.Bytes(), &poutput) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(testData, poutput) { t.Error("Test data and unmarshaled data are not equal") } } </ins>


// address is required. if len(spec.ServerAddressByClientCIDRs) == 0 { allErrs = append(allErrs, field.Required(fieldPath.Child("serverAddressByClientCIDRs"), "")) <ins> } else { for i, address := range spec.ServerAddressByClientCIDRs { idxPath := fieldPath.Child("serverAddressByClientCIDRs").Index(i) if len(address.ClientCIDR) > 0 { if _, _, err := net.ParseCIDR(address.ClientCIDR); err != nil { allErrs = append(allErrs, field.Invalid(idxPath.Child("clientCIDR"), address.ClientCIDR, fmt.Sprintf("must be a valid CIDR: %v", err))) } } } </ins> } return allErrs }


<del> // +build !cgo !linux </del> <ins> // +build !linux </ins> /* Copyright 2015 The Kubernetes Authors.


CPU utilization for the pod will not be defined and the autoscaler will not take any action. Further details of the autoscaling algorithm are given [here](../design/horizontal-pod-autoscaler.md#autoscaling-algorithm). <ins> Autoscaler uses heapster to collect CPU utilization. Therefore, it is required to deploy heapster monitoring in your cluster for autoscaling to work. </ins> Autoscaler accesses corresponding replication controller or deployment by scale sub-resource. Scale is an interface which allows to dynamically set the number of replicas and to learn the current state of them. More details on scale sub-resource can be found [here](../design/horizontal-pod-autoscaler.md#scale-subresource).


func prepareSubpathTarget(mounter Interface, subpath Subpath) (bool, string, error) { // Early check for already bind-mounted subpath. bindPathTarget := getSubpathBindTarget(subpath) <del> notMount, err := IsNotMountPoint(mounter, bindPathTarget) </del> <ins> notMount, err := mounter.IsNotMountPoint(bindPathTarget) </ins> if err != nil { if !os.IsNotExist(err) { return false, "", fmt.Errorf("error checking path %s for mount: %s", bindPathTarget, err)


[[constraint]] name = "github.com/modern-go/reflect2" <del> version = "1.0.0" </del> <ins> version = "1.0.1" </ins>


"description": "ServicePort contains information on service's port.", "properties": { "appProtocol": { <del> "description": "The application protocol for this port. This field follows standard Kubernetes label syntax. Un-prefixed names are reserved for IANA standard service names (as per RFC-6335 and http://www.iana.org/assignments/service-names). Non-standard protocols should use prefixed names such as mycompany.com/my-custom-protocol.", </del> <ins> "description": "The application protocol for this port. This field follows standard Kubernetes label syntax. Un-prefixed names are reserved for IANA standard service names (as per RFC-6335 and https://www.iana.org/assignments/service-names). Non-standard protocols should use prefixed names such as mycompany.com/my-custom-protocol.", </ins> "type": "string" }, "name": {


CreateTCPLoadBalancer(name, region string, externalIP net.IP, ports []int, hosts []string, affinityType api.AffinityType) (string, error) // UpdateTCPLoadBalancer updates hosts under the specified load balancer. UpdateTCPLoadBalancer(name, region string, hosts []string) error <del> // DeleteTCPLoadBalancer deletes a specified load balancer. DeleteTCPLoadBalancer(name, region string) error </del> <ins> // EnsureTCPLoadBalancerDeleted deletes the specified load balancer if it // exists, returning nil if the load balancer specified either didn't exist or // was successfully deleted. // This construction is useful because many cloud providers' load balancers // have multiple underlying components, meaning a Get could say that the LB // doesn't exist even if some part of it is still laying around. EnsureTCPLoadBalancerDeleted(name, region string) error </ins> } // Instances is an abstract, pluggable interface for sets of instances.


command: - /bin/sh - -c <del> - echo -998 > /proc/$$$/oom_score_adj && kube-proxy {{kubeconfig}} {{cluster_cidr}} --resource-container="" {{params}} 1>>/var/log/kube-proxy.log 2>&1 </del> <ins> - kube-proxy {{kubeconfig}} {{cluster_cidr}} --resource-container="" --oom-score-adj=-998 {{params}} 1>>/var/log/kube-proxy.log 2>&1 </ins> {{container_env}} {{kube_cache_mutation_detector_env_name}} {{kube_cache_mutation_detector_env_value}}


}) /* <del> Testname: allowPrivilegeEscalation=false. Description: Configuring the allowPrivilegeEscalation to false, does not allow the privilege escalation operation. A container is configured with allowPrivilegeEscalation=false and a given uid (1000) which is not 0. When the container is run, the container is run using uid=1000. This test is marked LinuxOnly since Windows does not support running as UID / GID, or privilege escalation. </del> <ins> Release : v1.15 Testname: Security Context, allowPrivilegeEscalation=false. Description: Configuring the allowPrivilegeEscalation to false, does not allow the privilege escalation operation. A container is configured with allowPrivilegeEscalation=false and a given uid (1000) which is not 0. When the container is run, container's output MUST match with expected output verifying container ran with given uid i.e. uid=1000. [LinuxOnly]: This test is marked LinuxOnly since Windows does not support running as UID / GID, or privilege escalation. </ins> */ <del> It("should not allow privilege escalation when false [LinuxOnly] [NodeConformance]", func() { </del> <ins> framework.ConformanceIt("should not allow privilege escalation when false [LinuxOnly] [NodeConformance]", func() { </ins> podName := "alpine-nnp-false-" + string(uuid.NewUUID()) apeFalse := false if err := createAndMatchOutput(podName, "Effective uid: 1000", &apeFalse, 1000); err != nil {


t.Run(test.name, func(t *testing.T) { serviceName := types.NamespacedName{Namespace: "default", Name: "myservice"} <del> sgList, err := c.buildELBSecurityGroupList(serviceName, "aid", test.extraSGsAnnotation) </del> <ins> sgList, err := c.buildELBSecurityGroupList(serviceName, "aid", test.annotations) </ins> assert.NoError(t, err, "buildELBSecurityGroupList failed") extraSGs := sgList[1:] assert.True(t, sets.NewString(test.expectedSGs...).Equal(sets.NewString(extraSGs...)),


// are set to 0. func completeRollingUpdate(set *apps.StatefulSet, status *apps.StatefulSetStatus) { if set.Spec.UpdateStrategy.Type == apps.RollingUpdateStatefulSetStrategyType && <del> status.UpdatedReplicas == status.Replicas && status.ReadyReplicas == status.Replicas { </del> <ins> status.UpdatedReplicas == *set.Spec.Replicas && status.ReadyReplicas == *set.Spec.Replicas && status.Replicas == *set.Spec.Replicas { </ins> status.CurrentReplicas = status.UpdatedReplicas status.CurrentRevision = status.UpdateRevision }


}) }) <del> Context("when pod using local volume with non-existant path", func() { ep := &eventPatterns{ reason:  "FailedMount", pattern: make([]string, 2)} ep.pattern = append(ep.pattern, "MountVolume.SetUp failed") ep.pattern = append(ep.pattern, "does not exist") It("should not be able to mount", func() { testVol := &localTestVolume{ node:            config.node0, hostDir:         "/non-existent/location/nowhere", localVolumeType: testVolType, } By("Creating local PVC and PV") createLocalPVCsPVs(config, []*localTestVolume{testVol}, testMode) pod, err := createLocalPod(config, testVol) Expect(err).To(HaveOccurred()) checkPodEvents(config, pod.Name, ep) verifyLocalVolume(config, testVol) cleanupLocalPVCsPVs(config, []*localTestVolume{testVol}) }) }) </del> <ins> }) } </ins> <del> Context("when pod's node is different from PV's NodeAffinity", func() { </del> <ins> Context("when local volume cannot be mounted [Slow]", func() { // TODO: // - make the pod create timeout shorter // - check for these errors in unit tests intead It("should fail mount due to non-existant path", func() { ep := &eventPatterns{ reason:  "FailedMount", pattern: make([]string, 2)} ep.pattern = append(ep.pattern, "MountVolume.SetUp failed") ep.pattern = append(ep.pattern, "does not exist") testVol := &localTestVolume{ node:            config.node0, hostDir:         "/non-existent/location/nowhere", localVolumeType: DirectoryLocalVolumeType, } By("Creating local PVC and PV") createLocalPVCsPVs(config, []*localTestVolume{testVol}, immediateMode) pod, err := createLocalPod(config, testVol) Expect(err).To(HaveOccurred()) checkPodEvents(config, pod.Name, ep) verifyLocalVolume(config, testVol) cleanupLocalPVCsPVs(config, []*localTestVolume{testVol}) }) </ins> <del> BeforeEach(func() { if len(config.nodes) < 2 { framework.Skipf("Runs only when number of nodes >= 2") } }) </del> <ins> It("should fail mount due to wrong node", func() { if len(config.nodes) < 2 { framework.Skipf("Runs only when number of nodes >= 2") } </ins> <del> ep := &eventPatterns{ reason:  "FailedScheduling", pattern: make([]string, 2)} ep.pattern = append(ep.pattern, "MatchNodeSelector") ep.pattern = append(ep.pattern, "VolumeNodeAffinityConflict") </del> <ins> ep := &eventPatterns{ reason:  "FailedMount", pattern: make([]string, 2)} ep.pattern = append(ep.pattern, "NodeSelectorTerm") ep.pattern = append(ep.pattern, "MountVolume.NodeAffinity check failed") </ins> <del> It("should not be able to mount due to different NodeAffinity", func() { testPodWithNodeName(config, testVolType, ep, config.nodes[1].Name, makeLocalPodWithNodeAffinity, testMode) }) </del> <ins> testVols := setupLocalVolumesPVCsPVs(config, DirectoryLocalVolumeType, config.node0, 1, immediateMode) testVol := testVols[0] </ins> <del> It("should not be able to mount due to different NodeSelector", func() { testPodWithNodeName(config, testVolType, ep, config.nodes[1].Name, makeLocalPodWithNodeSelector, testMode) }) </del> <ins> pod := makeLocalPodWithNodeName(config, testVol, config.nodes[1].Name) pod, err := config.client.CoreV1().Pods(config.ns).Create(pod) Expect(err).NotTo(HaveOccurred()) </ins> <del> }) </del> <ins> err = framework.WaitForPodNameRunningInNamespace(config.client, pod.Name, pod.Namespace) Expect(err).To(HaveOccurred()) checkPodEvents(config, pod.Name, ep) </ins> <del> Context("when pod's node is different from PV's NodeName", func() { </del> <ins> cleanupLocalVolumes(config, []*localTestVolume{testVol}) }) }) </ins> <del> BeforeEach(func() { if len(config.nodes) < 2 { framework.Skipf("Runs only when number of nodes >= 2") } }) </del> <ins> Context("when pod's node is different from PV's NodeAffinity", func() { var ( testVol    *localTestVolume volumeType localVolumeType ) BeforeEach(func() { if len(config.nodes) < 2 { framework.Skipf("Runs only when number of nodes >= 2") } </ins> <del> ep := &eventPatterns{ reason:  "FailedMount", pattern: make([]string, 2)} ep.pattern = append(ep.pattern, "NodeSelectorTerm") ep.pattern = append(ep.pattern, "MountVolume.NodeAffinity check failed") </del> <ins> volumeType = DirectoryLocalVolumeType setupStorageClass(config, &immediateMode) testVols := setupLocalVolumesPVCsPVs(config, volumeType, config.node0, 1, immediateMode) testVol = testVols[0] }) </ins> <del> It("should not be able to mount due to different NodeName", func() { testPodWithNodeName(config, testVolType, ep, config.nodes[1].Name, makeLocalPodWithNodeName, testMode) }) }) </del> <ins> AfterEach(func() { cleanupLocalVolumes(config, []*localTestVolume{testVol}) cleanupStorageClass(config) </ins> }) <del> } </del> <ins> It("should not be able to mount due to different NodeAffinity", func() { testPodWithNodeConflict(config, volumeType, config.nodes[1].Name, makeLocalPodWithNodeAffinity, immediateMode) }) It("should not be able to mount due to different NodeSelector", func() { testPodWithNodeConflict(config, volumeType, config.nodes[1].Name, makeLocalPodWithNodeSelector, immediateMode) }) }) </ins> Context("when using local volume provisioner", func() { var volumePath string


scheme := runtime.NewScheme() scheme.AddKnownTypes(cmResource.GroupVersion(), &v1.ConfigMap{}) codecs := serializer.NewCodecFactory(scheme) <del> o := NewFieldManagedObjectTracker(scheme, codecs.UniversalDecoder(), fakeTypeConverter) </del> <ins> o := NewFieldManagedObjectTracker(scheme, codecs.UniversalDecoder(), configMapTypeConverter(scheme)) </ins> reaction := ObjectReaction(o) action := NewCreateAction(cmResource, "default", &v1.ConfigMap{


minRequestTimeout:       minRequestTimeout, } crdInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ <ins> AddFunc:    ret.createCustomResourceDefinition, </ins> UpdateFunc: ret.updateCustomResourceDefinition, DeleteFunc: func(obj interface{}) { ret.removeDeadStorage()


"httpGet": { "host": "127.0.0.1", "port": 8080, <del> "path": "/healthz" </del> <ins> "path": "/healthz?exclude=etcd" </ins> }, "initialDelaySeconds": {{liveness_probe_initial_delay}}, "timeoutSeconds": 15 }, <ins> "readinessProbe": { "httpGet": { "host": "127.0.0.1", "port": 8080, "path": "/healthz" }, "timeoutSeconds": 15 }, </ins> "ports":[ { "name": "https", "containerPort": {{secure_port}},


func TestPodContainerDeviceAllocation(t *testing.T) { flag.Set("alsologtostderr", fmt.Sprintf("%t", true)) <del> var logLevel string flag.StringVar(&logLevel, "logLevel", "4", "test") flag.Lookup("v").Value.Set(logLevel) </del> res1 := TestResource{ resourceName:     "domain1.com/resource1", resourceQuantity: *resource.NewQuantity(int64(2), resource.DecimalSI),


timeoutCtx, timeoutCancel := context.WithTimeout(ctx, le.config.RenewDeadline) defer timeoutCancel() err := wait.PollImmediateUntil(le.config.RetryPeriod, func() (bool, error) { <del> return le.tryAcquireOrRenew(), nil </del> <ins> done := make(chan bool, 1) go func() { defer close(done) done <- le.tryAcquireOrRenew() }() select { case <-timeoutCtx.Done(): return false, fmt.Errorf("failed to tryAcquireOrRenew %s", timeoutCtx.Err()) case result := <-done: return result, nil } </ins> }, timeoutCtx.Done()) le.maybeReportTransition() desc := le.config.Lock.Describe() if err == nil {


out.Filter = (*v1alpha1.PluginSet)(unsafe.Pointer(in.Filter)) out.PostFilter = (*v1alpha1.PluginSet)(unsafe.Pointer(in.PostFilter)) out.Score = (*v1alpha1.PluginSet)(unsafe.Pointer(in.Score)) <del> out.NormalizeScore = (*v1alpha1.PluginSet)(unsafe.Pointer(in.NormalizeScore)) </del> out.Reserve = (*v1alpha1.PluginSet)(unsafe.Pointer(in.Reserve)) out.Permit = (*v1alpha1.PluginSet)(unsafe.Pointer(in.Permit)) out.PreBind = (*v1alpha1.PluginSet)(unsafe.Pointer(in.PreBind))


// +k8s:deepcopy-gen=package <del> package testing </del> <ins> package testing // import "k8s.io/apiserver/pkg/endpoints/testing" </ins>


return nameservers, searches, options, utilerrors.NewAggregate(allErrors) } <ins> // Reads a resolv.conf-like file and returns the DNS config options from it. // Returns an empty DNSConfig if the given resolverConfigFile is an empty string. func getDNSConfig(resolverConfigFile string) (*runtimeapi.DNSConfig, error) { var hostDNS, hostSearch, hostOptions []string // Get host DNS settings if resolverConfigFile != "" { f, err := os.Open(resolverConfigFile) if err != nil { klog.ErrorS(err, "Could not open resolv conf file.") return nil, err } defer f.Close() hostDNS, hostSearch, hostOptions, err = parseResolvConf(f) if err != nil { err := fmt.Errorf("Encountered error while parsing resolv conf file. Error: %w", err) klog.ErrorS(err, "Could not parse resolv conf file.") return nil, err } } return &runtimeapi.DNSConfig{ Servers:  hostDNS, Searches: hostSearch, Options:  hostOptions, }, nil } </ins> func getPodDNSType(pod *v1.Pod) (podDNSType, error) { dnsPolicy := pod.Spec.DNSPolicy switch dnsPolicy {


// if nodeAffinity.RequiredDuringSchedulingRequiredDuringExecution != nil { // 	nodeSelectorTerms := nodeAffinity.RequiredDuringSchedulingRequiredDuringExecution.NodeSelectorTerms // 	glog.V(10).Infof("Match for RequiredDuringSchedulingRequiredDuringExecution node selector terms %+v", nodeSelectorTerms) <del> // 	nodeAffinityMatches = NodeMatchesNodeSelectorTerms(node, nodeSelectorTerms) </del> <ins> // 	nodeAffinityMatches = nodeMatchesNodeSelectorTerms(node, nodeSelectorTerms) </ins> // } // Match node selector for requiredDuringSchedulingIgnoredDuringExecution. if nodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution != nil { nodeSelectorTerms := nodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms glog.V(10).Infof("Match for RequiredDuringSchedulingIgnoredDuringExecution node selector terms %+v", nodeSelectorTerms) <del> nodeAffinityMatches = nodeAffinityMatches && NodeMatchesNodeSelectorTerms(node, nodeSelectorTerms) </del> <ins> nodeAffinityMatches = nodeAffinityMatches && nodeMatchesNodeSelectorTerms(node, nodeSelectorTerms) </ins> } }


} } <ins> func TestAttacherWaitForAttach(t *testing.T) { tests := []struct { name             string driver           string makeAttachment   func() *storage.VolumeAttachment expectedAttachID string expectError      bool }{ { name:   "successful attach", driver: "attachable", makeAttachment: func() *storage.VolumeAttachment { testAttachID := getAttachmentName("test-vol", "attachable", "node") successfulAttachment := makeTestAttachment(testAttachID, "node", "test-pv") successfulAttachment.Status.Attached = true return successfulAttachment }, expectedAttachID: getAttachmentName("test-vol", "attachable", "node"), expectError:      false, }, { name:        "failed attach", driver:      "attachable", expectError: true, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { plug, _, tmpDir, _ := newTestWatchPlugin(t, nil) defer os.RemoveAll(tmpDir) attacher, err := plug.NewAttacher() if err != nil { t.Fatalf("failed to create new attacher: %v", err) } csiAttacher := attacher.(*csiAttacher) spec := volume.NewSpecFromPersistentVolume(makeTestPV("test-pv", 10, test.driver, "test-vol"), false) if test.makeAttachment != nil { attachment := test.makeAttachment() _, err = csiAttacher.k8s.StorageV1beta1().VolumeAttachments().Create(attachment) if err != nil { t.Fatalf("failed to create VolumeAttachment: %v", err) } gotAttachment, err := csiAttacher.k8s.StorageV1beta1().VolumeAttachments().Get(attachment.Name, meta.GetOptions{}) if err != nil { t.Fatalf("failed to get created VolumeAttachment: %v", err) } t.Logf("created test VolumeAttachment %+v", gotAttachment) } attachID, err := csiAttacher.WaitForAttach(spec, "", nil, time.Second) if err != nil && !test.expectError { t.Errorf("Unexpected error: %s", err) } if err == nil && test.expectError { t.Errorf("Expected error, got none") } if attachID != test.expectedAttachID { t.Errorf("Expected attachID %q, got %q", test.expectedAttachID, attachID) } }) } } </ins> func TestAttacherWaitForVolumeAttachment(t *testing.T) { nodeName := "test-node" testCases := []struct {


package gce import ( <ins> "net/http" "net/http/httptest" </ins> "reflect" "testing" compute "google.golang.org/api/compute/v1" <ins> "k8s.io/kubernetes/pkg/util/flowcontrol" </ins> "k8s.io/kubernetes/pkg/util/rand" <ins> utiltesting "k8s.io/kubernetes/pkg/util/testing" </ins> ) func TestGetRegion(t *testing.T) {


if err != nil { assert.NoErrorf(t, err, "unable to create temp file") } stdoutBuf := &bytes.Buffer{} stderrBuf := &bytes.Buffer{} containerID := "fake-container-id"


} // writeLogs writes logs into stdout, stderr. <del> func (w *logWriter) write(msg *logMessage) error { </del> <ins> func (w *logWriter) write(msg *logMessage, addPrefix bool) error { </ins> if msg.timestamp.Before(w.opts.since) { // Skip the line because it's older than since return nil } line := msg.log <del> if w.opts.timestamp { </del> <ins> if w.opts.timestamp && addPrefix { </ins> prefix := append([]byte(msg.timestamp.Format(timeFormatOut)), delimiter[0]) line = append(prefix, line...) }


// in node status. By calling this function (GetVolumesToReportAttached), node status should be updated, and the volume // will not need to be updated until new changes are applied (detach is triggered again) verifyVolumeAttachedToNode(t, generatedVolumeName, nodeName1, cache.AttachStateAttached, asw) <del> verifyVolumeReportedAsAttachedToNode(t, logger, generatedVolumeName, nodeName1, true, asw) </del> <ins> verifyVolumeReportedAsAttachedToNode(t, logger, generatedVolumeName, nodeName1, true, asw, volumeAttachedCheckTimeout) </ins> }


{"name" : "BalancedResourceAllocation", "weight" : 1}, {"name" : "ServiceSpreadingPriority", "weight" : 1}, {"name" : "EqualPriority", "weight" : 1} <del> ] </del> <ins> ], "hardPodAffinitySymmetricWeight" : 10 </ins> }


numErrs: 0, }, { <ins> name: "invalid duplicate targetports (number with same protocol)", tweakSvc: func(s *api.Service) { s.Spec.Type = api.ServiceTypeClusterIP s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 1, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}) s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "r", Port: 2, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}) }, numErrs: 1, }, { name: "invalid duplicate targetports (name with same protocol)", tweakSvc: func(s *api.Service) { s.Spec.Type = api.ServiceTypeClusterIP s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 1, Protocol: "TCP", TargetPort: intstr.FromString("http")}) s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "r", Port: 2, Protocol: "TCP", TargetPort: intstr.FromString("http")}) }, numErrs: 1, }, { name: "valid duplicate targetports (number with different protocols)", tweakSvc: func(s *api.Service) { s.Spec.Type = api.ServiceTypeClusterIP s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 1, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}) s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "r", Port: 2, Protocol: "UDP", TargetPort: intstr.FromInt(8080)}) }, numErrs: 0, }, { name: "valid duplicate targetports (name with different protocols)", tweakSvc: func(s *api.Service) { s.Spec.Type = api.ServiceTypeClusterIP s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 1, Protocol: "TCP", TargetPort: intstr.FromString("http")}) s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "r", Port: 2, Protocol: "UDP", TargetPort: intstr.FromString("http")}) }, numErrs: 0, }, { </ins> name: "valid type - cluster", tweakSvc: func(s *api.Service) { s.Spec.Type = api.ServiceTypeClusterIP


MASTER_IP="" MINION_IPS="" <ins> KUBECTL_PATH=${KUBE_ROOT}/cluster/ubuntu/binaries/kubectl </ins> # Assumed Vars: #   KUBE_ROOT function test-build-release {


pluginapi.RegisterDevicePluginServer(m.server, m) go m.server.Serve(sock) <del> // Wait till grpc server is ready. for i := 0; i < 10; i++ { services := m.server.GetServiceInfo() if len(services) > 0 { break } time.Sleep(1 * time.Second) </del> <ins> _, conn, err := dial(m.socket) if err != nil { return err </ins> } <ins> conn.Close() </ins> log.Println("Starting to serve on", m.socket) return nil


return c.check(r) } <ins> // getExcludedChecks extracts the health check names to be excluded from the query param func getExcludedChecks(r *http.Request) sets.String { checks, found := r.URL.Query()["exclude"] if found { return sets.NewString(checks...) } return sets.NewString() } </ins> // handleRootHealthz returns an http.HandlerFunc that serves the provided checks. func handleRootHealthz(checks ...HealthzChecker) http.HandlerFunc { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { failed := false <ins> excluded := getExcludedChecks(r) </ins> var verboseOut bytes.Buffer for _, check := range checks { <ins> // no-op the check if we've specified we want to exclude the check if excluded.Has(check.Name()) { excluded.Delete(check.Name()) fmt.Fprintf(&verboseOut, "[+]%v excluded: okn", check.Name()) continue } </ins> if err := check.Check(r); err != nil { // don't include the error since this endpoint is public.  If someone wants more detail // they should have explicit permission to the detailed checks.


// Score is a list of plugins that should be invoked when ranking nodes that have passed the filtering phase. Score *PluginSet <del> // NormalizeScore is a list of plugins that should be invoked after the scoring phase to normalize scores. NormalizeScore *PluginSet </del> // Reserve is a list of plugins invoked when reserving a node to run the pod. Reserve *PluginSet


}) nc.leaseLister = leaseInformer.Lister() <del> nc.leaseInformerSynced = leaseInformer.Informer().HasSynced </del> <ins> if utilfeature.DefaultFeatureGate.Enabled(features.NodeLease) { nc.leaseInformerSynced = leaseInformer.Informer().HasSynced } else { // Always indicate that lease is synced to prevent syncing lease. nc.leaseInformerSynced = func() bool { return true } } </ins> nc.nodeLister = nodeInformer.Lister() nc.nodeInformerSynced = nodeInformer.Informer().HasSynced


func TestIsCurrentInstance(t *testing.T) { cloud := &Cloud{ Config: Config{ <del> VMType: vmTypeVMSS, </del> <ins> VMType: vmTypeStandard, </ins> }, } testcases := []struct {


parameters[k] = v.(string) } } <ins> if snapshotProvider, ok := snapshotClass.Object["driver"]; ok { snapshotter = snapshotProvider.(string) } </ins> } return testsuites.GetSnapshotClass(snapshotter, parameters, ns, suffix)


}) // TODO: add tests that cover deployment.Spec.MinReadySeconds once we solved clock-skew issues // See https://github.com/kubernetes/kubernetes/issues/29229 <ins> ginkgo.It("should run the lifecycle of a Deployment", func() { deploymentResource := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"} testNamespaceName := f.Namespace.Name testDeploymentName := "test-deployment" testDeploymentInitialImage := imageutils.GetE2EImage(imageutils.Agnhost) testDeploymentPatchImage := imageutils.GetE2EImage(imageutils.Pause) testDeploymentUpdateImage := imageutils.GetE2EImage(imageutils.Httpd) testDeploymentDefaultReplicas := int32(3) testDeploymentMinimumReplicas := int32(1) testDeploymentNoReplicas := int32(0) testDeploymentLabels := map[string]string{"test-deployment-static": "true"} testDeploymentLabelsFlat := "test-deployment-static=true" testDeploymentLabelSelectors := metav1.LabelSelector{ MatchLabels: testDeploymentLabels, } w := &cache.ListWatch{ WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { options.LabelSelector = testDeploymentLabelsFlat return f.ClientSet.AppsV1().Deployments(testNamespaceName).Watch(context.TODO(), options) }, } deploymentsList, err := f.ClientSet.AppsV1().Deployments("").List(context.TODO(), metav1.ListOptions{LabelSelector: testDeploymentLabelsFlat}) framework.ExpectNoError(err, "failed to list Deployments") ginkgo.By("creating a Deployment") testDeployment := appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name:   testDeploymentName, Labels: map[string]string{"test-deployment-static": "true"}, }, Spec: appsv1.DeploymentSpec{ Replicas: &testDeploymentDefaultReplicas, Selector: &testDeploymentLabelSelectors, Template: v1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: testDeploymentLabelSelectors.MatchLabels, }, Spec: v1.PodSpec{ Containers: []v1.Container{{ Name:  testDeploymentName, Image: testDeploymentInitialImage, }}, }, }, }, } _, err = f.ClientSet.AppsV1().Deployments(testNamespaceName).Create(context.TODO(), &testDeployment, metav1.CreateOptions{}) framework.ExpectNoError(err, "failed to create Deployment %v in namespace %v", testDeploymentName, testNamespaceName) ginkgo.By("waiting for Deployment to be created") ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() _, err = watchtools.Until(ctx, deploymentsList.ResourceVersion, w, func(event watch.Event) (bool, error) { switch event.Type { case watch.Added: if deployment, ok := event.Object.(*appsv1.Deployment); ok { found := deployment.ObjectMeta.Name == testDeployment.Name && deployment.Labels["test-deployment-static"] == "true" return found, nil } default: framework.Logf("observed event type %v", event.Type) } return false, nil }) framework.ExpectNoError(err, "failed to see %v event", watch.Added) ginkgo.By("waiting for all Replicas to be Ready") ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second) defer cancel() _, err = watchtools.Until(ctx, deploymentsList.ResourceVersion, w, func(event watch.Event) (bool, error) { if deployment, ok := event.Object.(*appsv1.Deployment); ok { found := deployment.ObjectMeta.Name == testDeployment.Name && deployment.Labels["test-deployment-static"] == "true" && deployment.Status.AvailableReplicas == testDeploymentDefaultReplicas && deployment.Status.ReadyReplicas == testDeploymentDefaultReplicas return found, nil } return false, nil }) framework.ExpectNoError(err, "failed to see replicas of %v in namespace %v scale to requested amount of %v", testDeployment.Name, testNamespaceName, testDeploymentDefaultReplicas) ginkgo.By("patching the Deployment") deploymentPatch, err := json.Marshal(map[string]interface{}{ "metadata": map[string]interface{}{ "labels": map[string]string{"test-deployment": "patched"}, }, "spec": map[string]interface{}{ "replicas": testDeploymentMinimumReplicas, "template": map[string]interface{}{ "spec": map[string]interface{}{ "containers": [1]map[string]interface{}{{ "name":    testDeploymentName, "image":   testDeploymentPatchImage, "command": []string{"/bin/sleep", "100000"}, }}, }, }, }, }) framework.ExpectNoError(err, "failed to Marshal Deployment JSON patch") _, err = f.ClientSet.AppsV1().Deployments(testNamespaceName).Patch(context.TODO(), testDeploymentName, types.StrategicMergePatchType, []byte(deploymentPatch), metav1.PatchOptions{}) framework.ExpectNoError(err, "failed to patch Deployment") ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second) defer cancel() _, err = watchtools.Until(ctx, deploymentsList.ResourceVersion, w, func(event watch.Event) (bool, error) { switch event.Type { case watch.Modified: if deployment, ok := event.Object.(*appsv1.Deployment); ok { found := deployment.ObjectMeta.Name == testDeployment.Name && deployment.Labels["test-deployment-static"] == "true" return found, nil } default: framework.Logf("observed event type %v", event.Type) } return false, nil }) framework.ExpectNoError(err, "failed to see %v event", watch.Modified) ginkgo.By("waiting for Replicas to scale") ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second) defer cancel() _, err = watchtools.Until(ctx, deploymentsList.ResourceVersion, w, func(event watch.Event) (bool, error) { if deployment, ok := event.Object.(*appsv1.Deployment); ok { found := deployment.ObjectMeta.Name == testDeployment.Name && deployment.Labels["test-deployment-static"] == "true" && deployment.Status.AvailableReplicas == testDeploymentMinimumReplicas && deployment.Status.ReadyReplicas == testDeploymentMinimumReplicas && deployment.Spec.Template.Spec.Containers[0].Image == testDeploymentPatchImage return found, nil } return false, nil }) framework.ExpectNoError(err, "failed to see replicas of %v in namespace %v scale to requested amount of %v", testDeployment.Name, testNamespaceName, testDeploymentMinimumReplicas) ginkgo.By("listing Deployments") deploymentsList, err = f.ClientSet.AppsV1().Deployments("").List(context.TODO(), metav1.ListOptions{LabelSelector: testDeploymentLabelsFlat}) framework.ExpectNoError(err, "failed to list Deployments") foundDeployment := false for _, deploymentItem := range deploymentsList.Items { if deploymentItem.ObjectMeta.Name == testDeploymentName && deploymentItem.ObjectMeta.Namespace == testNamespaceName && deploymentItem.ObjectMeta.Labels["test-deployment-static"] == "true" { foundDeployment = true break } } framework.ExpectEqual(foundDeployment, true, "unable to find the Deployment in list", deploymentsList) ginkgo.By("updating the Deployment") testDeploymentUpdate := testDeployment testDeploymentUpdate.ObjectMeta.Labels["test-deployment"] = "updated" testDeploymentUpdate.Spec.Template.Spec.Containers[0].Image = testDeploymentUpdateImage testDeploymentDefaultReplicasPointer := &testDeploymentDefaultReplicas testDeploymentUpdate.Spec.Replicas = testDeploymentDefaultReplicasPointer testDeploymentUpdateUnstructuredMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&testDeploymentUpdate) framework.ExpectNoError(err, "failed to convert to unstructured") testDeploymentUpdateUnstructured := unstructuredv1.Unstructured{ Object: testDeploymentUpdateUnstructuredMap, } // currently this hasn't been able to hit the endpoint replaceAppsV1NamespacedDeploymentStatus _, err = dc.Resource(deploymentResource).Namespace(testNamespaceName).Update(context.TODO(), &testDeploymentUpdateUnstructured, metav1.UpdateOptions{}) //, "status") framework.ExpectNoError(err, "failed to update the DeploymentStatus") ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second) defer cancel() _, err = watchtools.Until(ctx, deploymentsList.ResourceVersion, w, func(event watch.Event) (bool, error) { switch event.Type { case watch.Modified: if deployment, ok := event.Object.(*appsv1.Deployment); ok { found := deployment.ObjectMeta.Name == testDeployment.Name && deployment.Labels["test-deployment-static"] == "true" return found, nil } default: framework.Logf("observed event type %v", event.Type) } return false, nil }) framework.ExpectNoError(err, "failed to see %v event", watch.Modified) ginkgo.By("fetching the DeploymentStatus") deploymentGetUnstructured, err := dc.Resource(deploymentResource).Namespace(testNamespaceName).Get(context.TODO(), testDeploymentName, metav1.GetOptions{}, "status") framework.ExpectNoError(err, "failed to fetch the Deployment") deploymentGet := appsv1.Deployment{} err = runtime.DefaultUnstructuredConverter.FromUnstructured(deploymentGetUnstructured.Object, &deploymentGet) framework.ExpectNoError(err, "failed to convert the unstructured response to a Deployment") framework.ExpectEqual(deploymentGet.Spec.Template.Spec.Containers[0].Image, testDeploymentUpdateImage, "failed to update image") framework.ExpectEqual(deploymentGet.ObjectMeta.Labels["test-deployment"], "updated", "failed to update labels") ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second) defer cancel() _, err = watchtools.Until(ctx, deploymentsList.ResourceVersion, w, func(event watch.Event) (bool, error) { if deployment, ok := event.Object.(*appsv1.Deployment); ok { found := deployment.ObjectMeta.Name == testDeployment.Name && deployment.Labels["test-deployment-static"] == "true" && deployment.Status.AvailableReplicas == testDeploymentDefaultReplicas && deployment.Status.ReadyReplicas == testDeploymentDefaultReplicas return found, nil } return false, nil }) framework.ExpectNoError(err, "failed to see replicas of %v in namespace %v scale to requested amount of %v", testDeployment.Name, testNamespaceName, testDeploymentDefaultReplicas) ginkgo.By("patching the DeploymentStatus") deploymentStatusPatch, err := json.Marshal(map[string]interface{}{ "metadata": map[string]interface{}{ "labels": map[string]string{"test-deployment": "patched-status"}, }, "status": map[string]interface{}{ "readyReplicas": testDeploymentNoReplicas, }, }) framework.ExpectNoError(err, "failed to Marshal Deployment JSON patch") dc.Resource(deploymentResource).Namespace(testNamespaceName).Patch(context.TODO(), testDeploymentName, types.StrategicMergePatchType, []byte(deploymentStatusPatch), metav1.PatchOptions{}, "status") ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second) defer cancel() _, err = watchtools.Until(ctx, deploymentsList.ResourceVersion, w, func(event watch.Event) (bool, error) { switch event.Type { case watch.Modified: if deployment, ok := event.Object.(*appsv1.Deployment); ok { found := deployment.ObjectMeta.Name == testDeployment.Name && deployment.Labels["test-deployment-static"] == "true" return found, nil } default: framework.Logf("observed event type %v", event.Type) } return false, nil }) framework.ExpectNoError(err, "failed to see %v event", watch.Modified) ginkgo.By("fetching the DeploymentStatus") deploymentGetUnstructured, err = dc.Resource(deploymentResource).Namespace(testNamespaceName).Get(context.TODO(), testDeploymentName, metav1.GetOptions{}, "status") framework.ExpectNoError(err, "failed to fetch the DeploymentStatus") deploymentGet = appsv1.Deployment{} err = runtime.DefaultUnstructuredConverter.FromUnstructured(deploymentGetUnstructured.Object, &deploymentGet) framework.ExpectNoError(err, "failed to convert the unstructured response to a Deployment") framework.ExpectEqual(deploymentGet.Spec.Template.Spec.Containers[0].Image, testDeploymentUpdateImage, "failed to update image") framework.ExpectEqual(deploymentGet.ObjectMeta.Labels["test-deployment"], "updated", "failed to update labels") ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second) defer cancel() _, err = watchtools.Until(ctx, deploymentsList.ResourceVersion, w, func(event watch.Event) (bool, error) { if deployment, ok := event.Object.(*appsv1.Deployment); ok { found := deployment.ObjectMeta.Name == testDeployment.Name && deployment.Labels["test-deployment-static"] == "true" && deployment.Status.AvailableReplicas == testDeploymentDefaultReplicas && deployment.Status.ReadyReplicas == testDeploymentDefaultReplicas && deployment.Spec.Template.Spec.Containers[0].Image == testDeploymentUpdateImage return found, nil } return false, nil }) framework.ExpectNoError(err, "failed to see replicas of %v in namespace %v scale to requested amount of %v", testDeployment.Name, testNamespaceName, testDeploymentDefaultReplicas) ginkgo.By("deleting the Deployment") err = f.ClientSet.AppsV1().Deployments(testNamespaceName).DeleteCollection(context.TODO(), metav1.DeleteOptions{}, metav1.ListOptions{LabelSelector: testDeploymentLabelsFlat}) framework.ExpectNoError(err, "failed to delete Deployment via collection") ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second) defer cancel() _, err = watchtools.Until(ctx, deploymentsList.ResourceVersion, w, func(event watch.Event) (bool, error) { switch event.Type { case watch.Deleted: if deployment, ok := event.Object.(*appsv1.Deployment); ok { found := deployment.ObjectMeta.Name == testDeployment.Name && deployment.Labels["test-deployment-static"] == "true" return found, nil } default: framework.Logf("observed event type %v", event.Type) } return false, nil }) framework.ExpectNoError(err, "failed to see %v event", watch.Deleted) }) </ins> }) func failureTrap(c clientset.Interface, ns string) {


// Makes sure the security group exists. // For multi-cluster isolation, name must be globally unique, for example derived from the service UUID. <ins> // Additional tags can be specified </ins> // Returns the security group id or error <del> func (c *Cloud) ensureSecurityGroup(name string, description string) (string, error) { </del> <ins> func (c *Cloud) ensureSecurityGroup(name string, description string, additionalTags map[string]string) (string, error) { </ins> groupID := "" attempt := 0 for {


err := esController.syncService(fmt.Sprintf("%s/%s", namespace, missingServiceName)) <del> // Since the service doesn't exist, we should get a not found error assert.NotNil(t, err, "Expected no error syncing service") assert.Equal(t, err.Error(), "service "notthere" not found") </del> <ins> // nil should be returned when the service doesn't exist assert.Nil(t, err, "Expected no error syncing service") </ins> // That should mean no client actions were performed assert.Len(t, client.Actions(), 0)


} } <del> if klog.V(4).Enabled() { </del> <ins> if klog.V(10).Enabled() { </ins> for i := range result { klog.InfoS("Calculated node's final score for pod", "pod", klog.KObj(pod), "node", result[i].Name, "score", result[i].Score) }


ginkgo.Context("once the node is setup", func() { ginkgo.It("container runtime's oom-score-adj should be -999", func() { runtimePids, err := getPidsForProcess(framework.TestContext.ContainerRuntimeProcessName, framework.TestContext.ContainerRuntimePidFile) <del> gomega.Expect(err).To(gomega.BeNil(), "failed to get list of container runtime pids") </del> <ins> framework.ExpectNoError(err, "failed to get list of container runtime pids") </ins> for _, pid := range runtimePids { gomega.Eventually(func() error { return validateOOMScoreAdjSetting(pid, -999)


} // Status indicates the result of running a plugin. It consists of a code, a <del> // message, (optionally) an error and an plugin name it fails by. When the status // code is not `Success`, the reasons should explain why. </del> <ins> // message, (optionally) an error and an plugin name it fails by. // When the status code is not Success, the reasons should explain why. // And, when code is Success, all the other fields should be empty. </ins> // NOTE: A nil Status is also considered as Success. type Status struct { code    Code


return false, output, nil } } <ins> // getRbdImageInfo try to get rbdImageInfo from deviceMountPath. func getRbdImageInfo(deviceMountPath string) (*rbdImageInfo, error) { deviceMountedPathSeps := strings.Split(filepath.Base(deviceMountPath), "-image-") if len(deviceMountedPathSeps) != 2 { return nil, fmt.Errorf("Can't found devicePath for %s ", deviceMountPath) } return &rbdImageInfo{ pool: deviceMountedPathSeps[0], name: deviceMountedPathSeps[1], }, nil } </ins>


return "", fmt.Errorf("created security group, but id was not returned: %s", name) } <del> err := c.tagging.createTags(c.ec2, groupID, ResourceLifecycleOwned, nil) </del> <ins> err := c.tagging.createTags(c.ec2, groupID, ResourceLifecycleOwned, additionalTags) </ins> if err != nil { // If we retry, ensureClusterTags will recover from this - it // will add the missing tags.  We could delete the security


"context" "fmt" "math/rand" <del> "sort" </del> "sync" "sync/atomic" "time"


} }) }) <ins> ginkgo.Context("PriorityClass endpoints", func() { var cs clientset.Interface f := framework.NewDefaultFramework("sched-preemption-path") var pcs []*schedulingv1.PriorityClass ginkgo.BeforeEach(func() { cs = f.ClientSet // Create 2 PriorityClass: p1, p2. for i := 1; i <= 2; i++ { name, val := fmt.Sprintf("p%d", i), int32(i) pc, err := cs.SchedulingV1().PriorityClasses().Create(context.TODO(), &schedulingv1.PriorityClass{ObjectMeta: metav1.ObjectMeta{Name: name}, Value: val}, metav1.CreateOptions{}) if err != nil { framework.Logf("Failed to create priority '%v/%v'. Reason: %v. Msg: %v", name, val, apierrors.ReasonForError(err), err) } framework.ExpectEqual(err == nil || apierrors.IsAlreadyExists(err), true) pcs = append(pcs, pc) } }) ginkgo.AfterEach(func() { // Print out additional info if tests failed. if ginkgo.CurrentGinkgoTestDescription().Failed { // List existing PriorityClasses. priorityList, err := cs.SchedulingV1().PriorityClasses().List(context.TODO(), metav1.ListOptions{}) if err != nil { framework.Logf("Unable to list PriorityClasses: %v", err) } else { framework.Logf("List existing PriorityClasses:") for _, p := range priorityList.Items { framework.Logf("%v/%v created at %v", p.Name, p.Value, p.CreationTimestamp) } } } // Cannot run collection deletion which would delete all system level priority classes. for _, pc := range pcs { err := cs.SchedulingV1().PriorityClasses().Delete(context.TODO(), pc.Name, *metav1.NewDeleteOptions(0)) framework.ExpectNoError(err) } }) ginkgo.It("verify PriorityClass endpoints can be operated with different HTTP methods", func() { // 1. Patch/Update on immutable fields will fail. pcCopy := pcs[0].DeepCopy() pcCopy.Value = pcCopy.Value * 10 err := patchPriorityClass(cs, pcs[0], pcCopy) framework.ExpectError(err, "expect a patch error on an immutable field") framework.Logf("%v", err) pcCopy = pcs[1].DeepCopy() pcCopy.Value = pcCopy.Value * 10 _, err = cs.SchedulingV1().PriorityClasses().Update(context.TODO(), pcCopy, metav1.UpdateOptions{}) framework.ExpectError(err, "expect an update error on an immutable field") framework.Logf("%v", err) // 2. Patch/Update on mutable fields will succeed. newDesc := "updated description" pcCopy = pcs[0].DeepCopy() pcCopy.Description = newDesc err = patchPriorityClass(cs, pcs[0], pcCopy) framework.ExpectNoError(err) pcCopy = pcs[1].DeepCopy() pcCopy.Description = newDesc _, err = cs.SchedulingV1().PriorityClasses().Update(context.TODO(), pcCopy, metav1.UpdateOptions{}) framework.ExpectNoError(err) // 3. List existing PriorityClasses. _, err = cs.SchedulingV1().PriorityClasses().List(context.TODO(), metav1.ListOptions{}) framework.ExpectNoError(err) // 4. Verify fields of updated PriorityClasses. for _, pc := range pcs { livePC, err := cs.SchedulingV1().PriorityClasses().Get(context.TODO(), pc.Name, metav1.GetOptions{}) framework.ExpectNoError(err) framework.ExpectEqual(livePC.Value, pc.Value) framework.ExpectEqual(livePC.Description, newDesc) } }) }) </ins> }) type pauseRSConfig struct {


"enableHttps": false, "nodeCacheCapable": false } <del> ] </del> <ins> ], "hardPodAffinitySymmetricWeight" : 10 </ins> }


// StoreCertsInSecrets is alpha in v1.8 StoreCertsInSecrets = "StoreCertsInSecrets" <ins> // SupportIPVSProxyMode is alpha in v1.8 SupportIPVSProxyMode = "SupportIPVSProxyMode" </ins> ) <del> var v190 = version.MustParseSemantic("v1.9.0") </del> <ins> var v190 = version.MustParseSemantic("v1.9.0-alpha.1") </ins> // InitFeatureGates are the default feature gates for the init command var InitFeatureGates = FeatureList{ <del> SelfHosting:         {FeatureSpec: utilfeature.FeatureSpec{Default: false, PreRelease: utilfeature.Beta}}, StoreCertsInSecrets: {FeatureSpec: utilfeature.FeatureSpec{Default: false, PreRelease: utilfeature.Alpha}}, HighAvailability:    {FeatureSpec: utilfeature.FeatureSpec{Default: false, PreRelease: utilfeature.Alpha}, MinimumVersion: v190}, </del> <ins> SelfHosting:          {FeatureSpec: utilfeature.FeatureSpec{Default: false, PreRelease: utilfeature.Beta}}, StoreCertsInSecrets:  {FeatureSpec: utilfeature.FeatureSpec{Default: false, PreRelease: utilfeature.Alpha}}, HighAvailability:     {FeatureSpec: utilfeature.FeatureSpec{Default: false, PreRelease: utilfeature.Alpha}, MinimumVersion: v190}, SupportIPVSProxyMode: {FeatureSpec: utilfeature.FeatureSpec{Default: false, PreRelease: utilfeature.Alpha}, MinimumVersion: v190}, </ins> } // Feature represents a feature being gated


} } <ins> // CloneTLSConfig returns a tls.Config with all exported fields except SessionTicketsDisabled and SessionTicketKey copied. // This makes it safe to call CloneTLSConfig on a config in active use by a server. // TODO: replace with tls.Config#Clone when we move to go1.8 func CloneTLSConfig(cfg *tls.Config) *tls.Config { if cfg == nil { return &tls.Config{} } return &tls.Config{ Rand:                     cfg.Rand, Time:                     cfg.Time, Certificates:             cfg.Certificates, NameToCertificate:        cfg.NameToCertificate, GetCertificate:           cfg.GetCertificate, RootCAs:                  cfg.RootCAs, NextProtos:               cfg.NextProtos, ServerName:               cfg.ServerName, ClientAuth:               cfg.ClientAuth, ClientCAs:                cfg.ClientCAs, InsecureSkipVerify:       cfg.InsecureSkipVerify, CipherSuites:             cfg.CipherSuites, PreferServerCipherSuites: cfg.PreferServerCipherSuites, ClientSessionCache:       cfg.ClientSessionCache, MinVersion:               cfg.MinVersion, MaxVersion:               cfg.MaxVersion, CurvePreferences:         cfg.CurvePreferences, } } </ins> func TLSClientConfig(transport http.RoundTripper) (*tls.Config, error) { if transport == nil { return nil, nil


fs.DurationVar(&s.ShutdownDelayDuration, "shutdown-delay-duration", s.ShutdownDelayDuration, ""+ "Time to delay the termination. During that time the server keeps serving requests normally and /healthz "+ <del> "returns success, but /readzy immediately returns failure. Graceful termination starts after this delay "+ </del> <ins> "returns success, but /readyz immediately returns failure. Graceful termination starts after this delay "+ </ins> "has elapsed. This can be used to allow load balancer to stop sending traffic to this server.") utilfeature.DefaultMutableFeatureGate.AddFlag(fs)


// unicode code point can be up to 4 bytes long) strWithMaxLength.MaxElements = zeroIfNegative(*s.MaxLength()) * 4 } else { <del> strWithMaxLength.MaxElements = estimateMaxStringLengthPerRequest(s) </del> <ins> if len(s.Enum()) > 0 { strWithMaxLength.MaxElements = estimateMaxStringEnumLength(s) } else { strWithMaxLength.MaxElements = estimateMaxStringLengthPerRequest(s) } </ins> } return strWithMaxLength case "boolean":


"fmt" "reflect" "strings" <ins> "testing" </ins> "time" apiextensions "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"


// createClients creates a kube client and an event client from the given config and masterOverride. // TODO remove masterOverride when CLI flags are removed. <del> func createClients(config componentconfig.ClientConnectionConfiguration, masterOverride string) (clientset.Interface, clientset.Interface, v1core.EventsGetter, error) { </del> <ins> func createClients(config componentconfig.ClientConnectionConfiguration, masterOverride string, timeout time.Duration) (clientset.Interface, clientset.Interface, v1core.EventsGetter, error) { </ins> if len(config.KubeConfigFile) == 0 && len(masterOverride) == 0 { glog.Warningf("Neither --kubeconfig nor --master was specified. Using default API client. This might not work.") }


currentBucketID := t.clock.Now().Unix() // There should be one or two elements in almost all cases expiredWatchers := make([][]*cacheWatcher, 0, 2) <ins> t.lock.Lock() defer t.lock.Unlock() </ins> for ; t.startBucketID <= currentBucketID; t.startBucketID++ { if watchers, ok := t.watchersBuckets[t.startBucketID]; ok { delete(t.watchersBuckets, t.startBucketID)


}, }, }, <ins> "invalid extended resource requirement without limit": { expectedError: "Limit must be set", spec: core.Pod{ ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns"}, Spec: core.PodSpec{ Containers: []core.Container{ { Name:            "invalid", Image:           "image", ImagePullPolicy: "IfNotPresent", Resources: core.ResourceRequirements{ Requests: core.ResourceList{ core.ResourceName("example.com/a"): resource.MustParse("2"), }, }, }, }, RestartPolicy: core.RestartPolicyAlways, DNSPolicy:     core.DNSClusterFirst, }, }, }, </ins> "invalid fractional extended resource in container request": { expectedError: "must be an integer", spec: core.Pod{


e26fc85d14a1d3dc25569831acc06919673c545a kube::util::go_install_from_commit  github.com/bazelbuild/rules_go/go/tools/gazelle/gazelle  <del> a280fbac1a0a4c67b0eee660b4fd1b3db7c9f058 </del> <ins> c72631a220406c4fae276861ee286aaec82c5af2 </ins> touch "${KUBE_ROOT}/vendor/BUILD"


if err := p.Unmarshal(data); err != nil { return err } <del> m.Time = time.Unix(p.Seconds, int64(p.Nanos)).Local() </del> <ins> // truncate precision to microseconds to match JSON marshaling/unmarshaling truncatedNanoseconds := time.Duration(p.Nanos).Truncate(time.Microsecond) m.Time = time.Unix(p.Seconds, int64(truncatedNanoseconds)).Local() </ins> return nil }


podName := "statscollectiontest-" + string(uuid.NewUUID()) pod := v1.Pod{ ObjectMeta: metav1.ObjectMeta{ <del> Name: podName, </del> <ins> Name: fmt.Sprintf("%s-%d", podName, i), </ins> Labels: map[string]string{ "name":    podName, "testapp": "stats-collection",


w = crlf.NewCRLFWriter(w) } <del> results.header.writeTo(w) </del> <ins> if addHeader { results.header.writeTo(w) } </ins> if !containsError { if err := printer.PrintObj(objToEdit, w); err != nil {


} func (m *NsenterMounter) IsNotMountPoint(dir string) (bool, error) { <del> return IsNotMountPoint(m, dir) </del> <ins> return isNotMountPoint(m, dir) </ins> } func (*NsenterMounter) IsMountPointMatch(mp MountPoint, dir string) bool {


func (c *FakeNamespaces) Create(namespace *api.Namespace) (*api.Namespace, error) { c.Fake.Actions = append(c.Fake.Actions, FakeAction{Action: "create-namespace"}) <del> return &api.Namespace{}, nil </del> <ins> return &api.Namespace{}, c.Fake.Err </ins> } func (c *FakeNamespaces) Update(namespace *api.Namespace) (*api.Namespace, error) {


if !skipAnyOf { for i := range v.AnyOf { <del> allErrs = append(allErrs, validateNestedValueValidation(&v.AnyOf[i], false, false, fldPath.Child("anyOf").Index(i))...) </del> <ins> allErrs = append(allErrs, validateNestedValueValidation(&v.AnyOf[i], false, false, lvl, fldPath.Child("anyOf").Index(i))...) </ins> } }


return err } <del> if pod.Status.Phase != api.PodRunning { return fmt.Errorf("pod %s is not running and cannot execute commands; current phase is %s", p.PodName, pod.Status.Phase) } </del> containerName := p.ContainerName if len(containerName) == 0 { glog.V(4).Infof("defaulting container name to %s", pod.Spec.Containers[0].Name)


cadvisorapi "github.com/google/cadvisor/info/v1" cadvisorapiv2 "github.com/google/cadvisor/info/v2" <ins> "github.com/stretchr/testify/assert" </ins> "k8s.io/kubernetes/pkg/api" apierrors "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/resource"


container_image( name = "image", <del> base = "@debian_jessie//image", </del> <ins> base = "@distroless_base//image", </ins> entrypoint = ["/kubemark"], files = ["//cmd/kubemark"], stamp = True,


"k8s.io/component-base/metrics" "k8s.io/klog/v2" podutil "k8s.io/kubernetes/pkg/api/v1/pod" <del> "k8s.io/kubernetes/pkg/apis/apps" </del> kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/prober/results" )


legacyregistry.MustRegister(DeprecatedEvictionStatsAge) legacyregistry.MustRegister(DeprecatedDevicePluginRegistrationCount) legacyregistry.MustRegister(DeprecatedDevicePluginAllocationLatency) <ins> legacyregistry.MustRegister(RunningContainerCount) legacyregistry.MustRegister(RunningPodCount) </ins> if utilfeature.DefaultFeatureGate.Enabled(features.DynamicKubeletConfig) { legacyregistry.MustRegister(AssignedConfig) legacyregistry.MustRegister(ActiveConfig)


apiVersion: v1 metadata: name: etcd <del> creationTimestamp: </del> labels: name: etcd spec:


kubetypes.HTTPSource, &api.Pod{ ObjectMeta: api.ObjectMeta{ <del> UID:       "111", Name:      "foo" + "-" + hostname, Namespace: "default", SelfLink: getSelfLink("foo-"+hostname, kubetypes.NamespaceDefault), </del> <ins> UID:         "111", Name:        "foo" + "-" + hostname, Namespace:   "default", Annotations: map[string]string{kubetypes.ConfigHashAnnotationKey: "111"}, SelfLink:    getSelfLink("foo-"+hostname, kubetypes.NamespaceDefault), </ins> }, Spec: api.PodSpec{ NodeName:                      hostname,


test.TestDynamicProvisioning() } <del> // Run the last test with storage.k8s.io/v1beta1 on pvc if betaTest != nil { ginkgo.By("Testing " + betaTest.Name + " with beta volume provisioning") betaClass := newBetaStorageClass(*betaTest, "beta") // create beta class manually betaClass, err := c.StorageV1beta1().StorageClasses().Create(context.TODO(), betaClass, metav1.CreateOptions{}) framework.ExpectNoError(err) defer deleteStorageClass(c, betaClass.Name) // fetch V1beta1 StorageClass as V1 object for the test class, err := c.StorageV1().StorageClasses().Get(context.TODO(), betaClass.Name, metav1.GetOptions{}) framework.ExpectNoError(err) betaTest.Client = c betaTest.Class = class betaTest.Claim = e2epv.MakePersistentVolumeClaim(e2epv.PersistentVolumeClaimConfig{ ClaimSize:        betaTest.ClaimSize, StorageClassName: &class.Name, VolumeMode:       &betaTest.VolumeMode, }, ns) betaTest.Claim.Spec.StorageClassName = &(class.Name) (*betaTest).TestDynamicProvisioning() } </del> }) ginkgo.It("should provision storage with non-default reclaim policy Retain", func() {


IP address. release: v1.9 file: test/e2e/common/pods.go <ins> - testname: Pods, completes the lifecycle of a Pod and the PodStatus codename: '[k8s.io] Pods should run through the lifecycle of Pods and PodStatus [Conformance]' description: A Pod is created with a static label which MUST succeed. It MUST succeed when patching the label and the pod data. When checking and replacing the PodStatus it MUST succeed. It MUST succeed when deleting the Pod. release: v1.20 file: test/e2e/common/pods.go </ins> - testname: Pods, remote command execution over websocket codename: '[k8s.io] Pods should support remote command execution over websockets [NodeConformance] [Conformance]'


fi } <del> function kube::build::probe_address { # Apple has an ancient version of netcat with custom timeout flags.  This is # the best way I (jbeda) could find to test for that. local netcat if nc 2>&1 | grep -e 'apple' >/dev/null ; then netcat="nc -G 1" else netcat="nc -w 1" fi </del> <ins> function kube::build::rsync_probe { </ins> # Wait unil rsync is up and running. <del> if ! which nc >/dev/null ; then V=6 kube::log::info "netcat not installed, waiting for 1s" sleep 1 return 0 fi local tries=10 </del> <ins> local tries=20 </ins> while (( ${tries} > 0 )) ; do <del> if ${netcat} -z "$1" "$2" 2> /dev/null ; then </del> <ins> if rsync "rsync://k8s@${1}:${2}/"  --password-file="${LOCAL_OUTPUT_BUILD_CONTEXT}/rsyncd.password"  &> /dev/null ; then </ins> return 0 fi tries=$(( ${tries} - 1))


echo "ELASTICSEARCH_LOGGING_REPLICAS='${ELASTICSEARCH_LOGGING_REPLICAS:-1}'" echo "ENABLE_NODE_LOGGING='${ENABLE_NODE_LOGGING:-false}'" echo "ENABLE_CLUSTER_UI='${ENABLE_CLUSTER_UI}'" <ins> echo "ENABLE_HOSTPATH_PROVISIONER='${ENABLE_HOSTPATH_PROVISIONER:-false}'" </ins> echo "LOGGING_DESTINATION='${LOGGING_DESTINATION:-}'" echo "ENABLE_CLUSTER_DNS='${ENABLE_CLUSTER_DNS:-false}'" echo "DNS_SERVER_IP='${DNS_SERVER_IP:-}'"


// Never send a bookmark event if we did not see an event here, this is fine // because we don't provide any guarantees on sending bookmarks. if lastProcessedResourceVersion == 0 { <ins> // pop expired watchers in case there has been no update c.bookmarkWatchers.popExpiredWatchers() </ins> continue } bookmarkEvent := &watchCacheEvent{


"where N means number of retries allowed for kubelet to post node status.") fs.Float32Var(&o.NodeEvictionRate, "node-eviction-rate", 0.1, "Number of nodes per second on which pods are deleted in case of node failure when a zone is healthy (see --unhealthy-zone-threshold for definition of healthy/unhealthy). Zone refers to entire cluster in non-multizone clusters.") fs.Float32Var(&o.SecondaryNodeEvictionRate, "secondary-node-eviction-rate", 0.01, "Number of nodes per second on which pods are deleted in case of node failure when a zone is unhealthy (see --unhealthy-zone-threshold for definition of healthy/unhealthy). Zone refers to entire cluster in non-multizone clusters. This value is implicitly overridden to 0 if the cluster size is smaller than --large-cluster-size-threshold.") <del> fs.Int32Var(&o.LargeClusterSizeThreshold, "large-cluster-size-threshold", 50, fmt.Sprintf("Number of nodes from which %s treats the cluster as large for the eviction logic purposes. --secondary-node-eviction-rate is implicitly overridden to 0 for clusters this size or smaller.", names.NodeLifecycleController)) </del> <ins> fs.Int32Var(&o.LargeClusterSizeThreshold, "large-cluster-size-threshold", 50, fmt.Sprintf("Number of nodes from which %s treats the cluster as large for the eviction logic purposes. --secondary-node-eviction-rate is implicitly overridden to 0 for clusters this size or smaller. Notice: If nodes reside in multiple zones, this threshold will be considered as zone node size threshold for each zone to determine node eviction rate independently.", names.NodeLifecycleController)) </ins> fs.Float32Var(&o.UnhealthyZoneThreshold, "unhealthy-zone-threshold", 0.55, "Fraction of Nodes in a zone which needs to be not Ready (minimum 3) for zone to be treated as unhealthy. ") }


// +optional optional string workingDir = 5; <del> // List of ports to expose from the container. Exposing a port here gives // the system additional information about the network connections a // container uses, but is primarily informational. Not specifying a port here </del> <ins> // List of ports to expose from the container. Not specifying a port here </ins> // DOES NOT prevent that port from being exposed. Any port which is // listening on the default "0.0.0.0" address inside a container will be // accessible from the network. <ins> // Modifying this array with strategic merge patch may corrupt the data. // For more information See https://github.com/kubernetes/kubernetes/issues/108255. </ins> // Cannot be updated. // +optional // +patchMergeKey=containerPort


} return ret } <del> func getPodLabelName(pod *v1.Pod) string { podName := pod.Name if pod.GenerateName != "" { podNameSlice := strings.Split(pod.Name, "-") podName = strings.Join(podNameSlice[:len(podNameSlice)-1], "-") if label, ok := pod.GetLabels()[apps.DefaultDeploymentUniqueLabelKey]; ok { podName = strings.ReplaceAll(podName, fmt.Sprintf("-%s", label), "") } } return podName } </del>


} // If the container logs directory does not exist, create it. <del> if _, err := os.Stat(containerLogsDir); err != nil { if err := kl.os.MkdirAll(containerLogsDir, 0755); err != nil { glog.Errorf("Failed to create directory %q: %v", containerLogsDir, err) </del> <ins> if _, err := os.Stat(ContainerLogsDir); err != nil { if err := kl.os.MkdirAll(ContainerLogsDir, 0755); err != nil { glog.Errorf("Failed to create directory %q: %v", ContainerLogsDir, err) </ins> } }


// wait until new webhook is called the first time if err := wait.PollImmediate(time.Millisecond*5, wait.ForeverTestTimeout, func() (bool, error) { <del> _, err = client.CoreV1().Pods("default").Patch(reinvocationMarkerFixture.Name, types.JSONPatchType, []byte("[]")) </del> <ins> _, err = client.CoreV1().Pods(markerNs).Patch(marker.Name, types.JSONPatchType, []byte("[]")) </ins> select { case <-upCh: return true, nil


<ins> # Development Guide # Releases and Official Builds Official releases are built in Docker containers.  Details are [here](build/README.md).  You can do simple builds and development with just a local Docker installation.  If want to build go locally outside of docker, please continue below. ## Go development environment Kubernetes is written in [Go](http://golang.org) programming language. If you haven't set up Go development environment, please follow [this instruction](http://golang.org/doc/code.html) to install go tool and set up GOPATH. Ensure your version of Go is at least 1.3. ## Put kubernetes into GOPATH We highly recommend to put kubernetes' code into your GOPATH. For example, the following commands will download kubernetes' code under the current user's GOPATH (Assuming there's only one directory in GOPATH.): ``` $ echo $GOPATH /home/user/goproj $ mkdir -p $GOPATH/src/github.com/GoogleCloudPlatform/ $ cd $GOPATH/src/github.com/GoogleCloudPlatform/ $ git clone git@github.com:GoogleCloudPlatform/kubernetes.git ``` The commands above will not work if there are more than one directory in ``$GOPATH``. (Obviously, clone your own fork of Kubernetes if you plan to do development.) ## godep and dependency management Kubernetes uses [godep](https://github.com/tools/godep) to manage dependencies. It is not strictly required for building Kubernetes but it is required when managing dependencies under the Godeps/ tree, and is required by a number of the build and test scripts. Please make sure that ``godep`` is installed and in your ``$PATH``. ### Installing godep There are many ways to build and host go binaries. Here is an easy way to get utilities like ```godep``` installed: 1. Ensure that [mercurial](http://mercurial.selenic.com/wiki/Download) is installed on your system. (some of godep's dependencies use the mercurial source control system).  Use ```apt-get install mercurial``` or ```yum install mercurial``` on Linux, or [brew.sh](http://brew.sh) on OS X, or download directly from mercurial. 2. Create a new GOPATH for your tools and install godep: ``` export GOPATH=$HOME/go-tools mkdir -p $GOPATH go get github.com/tools/godep ``` 3. Add $GOPATH/bin to your path. Typically you'd add this to your ~/.profile: ``` export GOPATH=$HOME/go-tools export PATH=$PATH:$GOPATH/bin ``` ### Using godep Here is a quick summary of `godep`.  `godep` helps manage third party dependencies by copying known versions into Godeps/_workspace.  You can use `godep` in three ways: 1. Use `godep` to call your `go` commands.  For example: `godep go test ./...` 2. Use `godep` to modify your `$GOPATH` so that other tools know where to find the dependencies.  Specifically: `export GOPATH=$GOPATH:$(godep path)` 3. Use `godep` to copy the saved versions of packages into your `$GOPATH`.  This is done with `godep restore`. We recommend using options #1 or #2. ## Hooks Before committing any changes, please link/copy these hooks into your .git directory. This will keep you from accidentally committing non-gofmt'd go code. ``` cd kubernetes ln -s hooks/prepare-commit-msg .git/hooks/prepare-commit-msg ln -s hooks/commit-msg .git/hooks/commit-msg ``` ## Unit tests ``` cd kubernetes hack/test-go.sh ``` Alternatively, you could also run: ``` cd kubernetes godep go test ./... ``` If you only want to run unit tests in one package, you could run ``godep go test`` under the package directory. For example, the following commands will run all unit tests in package kubelet: ``` $ cd kubernetes # step into kubernetes' directory. $ cd pkg/kubelet $ godep go test # some output from unit tests PASS ok      github.com/GoogleCloudPlatform/kubernetes/pkg/kubelet   0.317s ``` ## Coverage ``` cd kubernetes godep go tool cover -html=target/c.out ``` ## Integration tests You need an etcd somewhere in your PATH. To install etcd, run: ``` cd kubernetes hack/install-etcd.sh sudo ln -s $(pwd)/third_party/etcd/bin/etcd /usr/bin/etcd ``` ``` cd kubernetes hack/test-integration.sh ``` ## End-to-End tests You can run an end-to-end test which will bring up a master and two minions, perform some tests, and then tear everything down. Make sure you have followed the getting started steps for your chosen cloud platform (which might involve changing the `KUBERNETES_PROVIDER` environment variable to something other than "gce". ``` cd kubernetes hack/e2e-test.sh ``` Pressing control-C should result in an orderly shutdown but if something goes wrong and you still have some VMs running you can force a cleanup with the magical incantation: ``` hack/e2e-test.sh 1 1 1 ``` ## Testing out flaky tests [Instructions here](docs/devel/flaky-tests.md) ## Add/Update dependencies Kubernetes uses [godep](https://github.com/tools/godep) to manage dependencies. To add or update a package, please follow the instructions on [godep's document](https://github.com/tools/godep). To add a new package ``foo/bar``: - Make sure the kubernetes' root directory is in $GOPATH/github.com/GoogleCloudPlatform/kubernetes - Run ``godep restore`` to make sure you have all dependancies pulled. - Download foo/bar into the first directory in GOPATH: ``go get foo/bar``. - Change code in kubernetes to use ``foo/bar``. - Run ``godep save ./...`` under kubernetes' root directory. To update a package ``foo/bar``: - Make sure the kubernetes' root directory is in $GOPATH/github.com/GoogleCloudPlatform/kubernetes - Run ``godep restore`` to make sure you have all dependancies pulled. - Update the package with ``go get -u foo/bar``. - Change code in kubernetes accordingly if necessary. - Run ``godep update foo/bar`` under kubernetes' root directory. ## Keeping your development fork in sync One time after cloning your forked repo: ``` git remote add upstream https://github.com/GoogleCloudPlatform/kubernetes.git ``` Then each time you want to sync to upstream: ``` git fetch upstream git rebase upstream/master ``` ## Regenerating the API documentation ``` cd kubernetes/api sudo docker build -t kubernetes/raml2html . sudo docker run --name="docgen" kubernetes/raml2html sudo docker cp docgen:/data/kubernetes.html . ``` View the API documentation using htmlpreview (works on your fork, too): ``` http://htmlpreview.github.io/?https://github.com/GoogleCloudPlatform/kubernetes/blob/master/api/kubernetes.html ``` </ins>


if err != nil { return false, fmt.Errorf("got error while getting pod events: %s", err) } <del> if len(events.Items) == 0 { return false, nil // no events have occurred yet </del> <ins> for _, event := range events.Items { if strings.Contains(event.Message, msg) { return true, nil } </ins> } <del> return strings.Contains(events.Items[0].Message, msg), nil </del> <ins> return false, nil </ins> } }


import ( "bytes" <ins> "errors" </ins> "fmt" "math/rand" "net"


<ins> //go:build !providerless // +build !providerless /* Copyright 2023 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package vsphere import ( "testing" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes/fake" "k8s.io/legacy-cloud-providers/vsphere/vclib" ) // Annotation used to distinguish nodes in node cache / informer / API server const nodeAnnotation = "test" func getNode(annotation string) *v1.Node { return &v1.Node{ ObjectMeta: metav1.ObjectMeta{ Name: "node1", Annotations: map[string]string{ nodeAnnotation: annotation, }, }, } } func TestGetNode(t *testing.T) { tests := []struct { name           string cachedNodes    []*v1.Node informerNodes  []*v1.Node // "nil" means that the NodeManager has no nodeLister apiServerNodes []*v1.Node // "nil" means that the NodeManager has no nodeGetter expectedNodeAnnotation string expectNotFound         bool }{ { name:           "No cached node anywhere", cachedNodes:    []*v1.Node{}, informerNodes:  []*v1.Node{}, apiServerNodes: []*v1.Node{}, expectNotFound: true, }, { name:           "No lister & getter", cachedNodes:    []*v1.Node{}, informerNodes:  nil, apiServerNodes: nil, expectNotFound: true, }, { name:                   "cache is used first", cachedNodes:            []*v1.Node{getNode("cache")}, informerNodes:          []*v1.Node{getNode("informer")}, apiServerNodes:         []*v1.Node{getNode("apiserver")}, expectedNodeAnnotation: "cache", }, { name:                   "informer is used second", cachedNodes:            []*v1.Node{}, informerNodes:          []*v1.Node{getNode("informer")}, apiServerNodes:         []*v1.Node{getNode("apiserver")}, expectedNodeAnnotation: "informer", }, { name:                   "API server is used last", cachedNodes:            []*v1.Node{}, informerNodes:          []*v1.Node{}, apiServerNodes:         []*v1.Node{getNode("apiserver")}, expectedNodeAnnotation: "apiserver", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { // local NodeManager cache cache := make(map[string]*v1.Node) for _, node := range test.cachedNodes { cache[node.Name] = node } // Client with apiServerNodes objs := []runtime.Object{} for _, node := range test.apiServerNodes { objs = append(objs, node) } client := fake.NewSimpleClientset(objs...) nodeGetter := client.CoreV1() // Informer + nodeLister. Despite the client already has apiServerNodes, they won't appear in the // nodeLister, because the informer is never started. factory := informers.NewSharedInformerFactory(client, 0 /* no resync */) nodeInformer := factory.Core().V1().Nodes() for _, node := range test.informerNodes { nodeInformer.Informer().GetStore().Add(node) } nodeLister := nodeInformer.Lister() nodeManager := NodeManager{ registeredNodes: cache, } if test.informerNodes != nil { nodeManager.SetNodeLister(nodeLister) } if test.apiServerNodes != nil { nodeManager.SetNodeGetter(nodeGetter) } node, err := nodeManager.GetNode("node1") if test.expectNotFound && err != vclib.ErrNoVMFound { t.Errorf("Expected NotFound error, got: %v", err) } if !test.expectNotFound && err != nil { t.Errorf("Unexpected error: %s", err) } if test.expectedNodeAnnotation != "" { if node.Annotations == nil { t.Errorf("Expected node with annotation %q, got nil", test.expectedNodeAnnotation) } else { if ann := node.Annotations[nodeAnnotation]; ann != test.expectedNodeAnnotation { t.Errorf("Expected node with annotation %q, got %q", test.expectedNodeAnnotation, ann) } } } }) } } </ins>


nodeName k8stypes.NodeName, isAttached bool, asw cache.ActualStateOfWorld, <ins> timeout time.Duration, </ins> ) { <del> result := false volumes := asw.GetVolumesToReportAttached(logger) for _, volume := range volumes[nodeName] { if volume.Name == volumeName { result = true </del> <ins> var result bool var lastErr error err := wait.PollUntilContextTimeout(context.TODO(), 50*time.Millisecond, timeout, false, func(context.Context) (done bool, err error) { volumes := asw.GetVolumesToReportAttached(logger) for _, volume := range volumes[nodeName] { if volume.Name == volumeName { result = true } </ins> } <del> } if result == isAttached { t.Logf("Volume <%v> is reported as attached to node <%v>: %v", volumeName, nodeName, result) return </del> <ins> if result == isAttached { t.Logf("Volume <%v> is reported as attached to node <%v>: %v", volumeName, nodeName, result) return true, nil } lastErr = fmt.Errorf("Check volume <%v> is reported as attached to node <%v>, got %v, expected %v", volumeName, nodeName, result, isAttached) return false, nil }) if err != nil { t.Fatalf("last error: %q, wait timeout: %q", lastErr, err.Error()) </ins> } <del> t.Fatalf("Check volume <%v> is reported as attached to node <%v>, got %v, expected %v", volumeName, nodeName, result, isAttached) </del> }


"github.com/google/go-cmp/cmp" "k8s.io/apimachinery/pkg/util/json" "k8s.io/apimachinery/pkg/util/sets" <ins> "k8s.io/apimachinery/pkg/util/wait" </ins> "k8s.io/apimachinery/pkg/util/waitgroup" auditinternal "k8s.io/apiserver/pkg/apis/audit" "k8s.io/apiserver/pkg/audit"


// ExcludeMasterFromStandardLB excludes master nodes from standard load balancer. // If not set, it will be default to true. ExcludeMasterFromStandardLB *bool `json:"excludeMasterFromStandardLB" yaml:"excludeMasterFromStandardLB"` <ins> // DisableOutboundSNAT disables the outbound SNAT for public load balancer rules. // It should only be set when loadBalancerSku is standard. If not set, it will be default to false. DisableOutboundSNAT *bool `json:"disableOutboundSNAT" yaml:"disableOutboundSNAT"` </ins> // Maximum allowed LoadBalancer Rule Count is the limit enforced by Azure Load balancer MaximumLoadBalancerRuleCount int `json:"maximumLoadBalancerRuleCount" yaml:"maximumLoadBalancerRuleCount"`


# Clean up kubectl delete jobs pi "${kube_flags[@]}" # Post-condition: no pods exist. <del> kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" '' </del> <ins> kube::test::wait_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" '' </ins> # Pre-Condition: no Deployment exists kube::test::get_object_assert deployment "{{range.items}}{{$id_field}}:{{end}}" ''


for _, testcase := range testcases { t.Run(testcase.name, func(t *testing.T) { <del> buf := new(bytes.Buffer) errBuf := new(bytes.Buffer) </del> <ins> buf := new(buffer) errBuf := new(buffer) </ins> klog.SetOutputBySeverity("INFO", buf) klog.SetOutputBySeverity("WARNING", errBuf)


// Flaky operation failures in an e2e test can be captured through this. flakeReport *FlakeReport <del> // To make sure that this framework cleans up after itself, no matter what, // we install a Cleanup action before each test and clear it after.  If we // should abort, the AfterSuite hook should run all Cleanup actions. cleanupHandle CleanupActionHandle </del> // afterEaches is a map of name to function to be called after each test.  These are not // cleared.  The call order is randomized so that no dependencies can grow between // the various afterEaches


if err != nil { t.Fatalf("Failed to create scheduler: %v", err) } <ins> // Profiles </ins> profiles := make([]string, 0, len(s.Profiles)) for name := range s.Profiles { profiles = append(profiles, name)


defaultPodResourcesPath    = "/var/lib/kubelet/pod-resources" defaultPodResourcesTimeout = 10 * time.Second defaultPodResourcesMaxSize = 1024 * 1024 * 16 // 16 Mb <ins> kubeletReadOnlyPort        = "10255" kubeletHealthCheckURL      = "http://127.0.0.1:" + kubeletReadOnlyPort + "/healthz" </ins> ) func getNodeSummary() (*stats.Summary, error) {


} // if we're trying to hit the kube-apiserver and there wasn't an explicit config, use the in-cluster config <del> if server == "kubernetes.default.svc" { </del> <ins> if target == "kubernetes.default.svc" { </ins> // if we can find an in-cluster-config use that.  If we can't, fall through. inClusterConfig, err := rest.InClusterConfig() if err == nil {


} } <ins> // printPodsMultiline prints multiple pods with a proper alignment. func printPodsMultiline(w PrefixWriter, title string, pods []api.Pod) { printPodsMultilineWithIndent(w, "", title, "t", pods) } // printPodsMultilineWithIndent prints multiple pods with a user-defined alignment. func printPodsMultilineWithIndent(w PrefixWriter, initialIndent, title, innerIndent string, pods []api.Pod) { w.Write(LEVEL_0, "%s%s:%s", initialIndent, title, innerIndent) if pods == nil || len(pods) == 0 { w.WriteLine("<none>") return } // to print pods in the sorted order sort.Slice(pods, func(i, j int) bool { cmpKey := func(pod api.Pod) string { return pod.Name } return cmpKey(pods[i]) < cmpKey(pods[j]) }) for i, pod := range pods { if i != 0 { w.Write(LEVEL_0, "%s", initialIndent) w.Write(LEVEL_0, "%s", innerIndent) } w.Write(LEVEL_0, "%sn", pod.Name) } } </ins> // printPodTolerationsMultiline prints multiple tolerations with a proper alignment. func printPodTolerationsMultiline(w PrefixWriter, title string, tolerations []api.Toleration) { printTolerationsMultilineWithIndent(w, "", title, "t", tolerations)


NoSnatTestProxy          = ImageConfig{e2eRegistry, "no-snat-test-proxy", "1.0", true} NWayHTTP                 = ImageConfig{e2eRegistry, "n-way-http", "1.0", true} // When these values are updated, also update cmd/kubelet/app/options/options.go <del> Pause               = ImageConfig{gcRegistry, "pause", "3.0", false} </del> <ins> Pause               = ImageConfig{gcRegistry, "pause", "3.0", true} </ins> Porter              = ImageConfig{e2eRegistry, "porter", "1.0", true} PortForwardTester   = ImageConfig{e2eRegistry, "port-forward-tester", "1.0", true} Redis               = ImageConfig{e2eRegistry, "redis", "1.0", true}


import ( "context" "fmt" <del> "strconv" </del> <ins> "os" </ins> "strings" v1 "k8s.io/api/core/v1"


// list all pods to include the pods that don't match the rc's selector // anymore but has the stale controller ref. // TODO: Do the List and Filter in a single pass, or use an index. <del> pods, err := rm.podLister.Pods(rc.Namespace).List(labels.Everything()) </del> <ins> allPods, err := rm.podLister.Pods(rc.Namespace).List(labels.Everything()) </ins> if err != nil { return err } // Ignore inactive pods. var filteredPods []*v1.Pod <del> for _, pod := range pods { </del> <ins> for _, pod := range allPods { </ins> if controller.IsPodActive(pod) { filteredPods = append(filteredPods, pod) }


"time" v1 "k8s.io/api/core/v1" <ins> apierrors "k8s.io/apimachinery/pkg/api/errors" </ins> metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" utilfeature "k8s.io/apiserver/pkg/util/feature"


<ins> # See the OWNERS docs at https://go.k8s.io/owners approvers: - lavalamp - smarterclayton - deads2k - sttts - liggitt - caesarxuchao reviewers: - thockin - lavalamp - smarterclayton - wojtek-t - deads2k - derekwaynecarr - caesarxuchao - cheftako - mikedanese - liggitt - gmarek - sttts - ncdc - logicalhan - tallclair labels: - sig/api-machinery </ins>  No newline at end of file


kubectl get pods "${kube_flags[@]}" -lname=redis-master | grep -q 'redis-master' [ ! $(delete pods --all pods -l name=redis-master) ]   # not --all and label selector together kubectl delete --all pods "${kube_flags[@]}" # --all remove all the pods <ins> kubectl create -f examples/guestbook/redis-master.json "${kube_flags[@]}" kubectl create -f examples/redis/redis-proxy.yaml "${kube_flags[@]}" kubectl get pods redis-master redis-proxy "${kube_flags[@]}" kubectl delete pods redis-master redis-proxy # delete multiple pods at once howmanypods="$(kubectl get pods  -o template -t "{{ len .items }}" "${kube_flags[@]}")" [ "$howmanypods" -eq 0 ] kubectl create -f examples/guestbook/redis-master.json "${kube_flags[@]}" kubectl create -f examples/redis/redis-proxy.yaml "${kube_flags[@]}" kubectl stop pods redis-master redis-proxy # stop multiple pods at once </ins> howmanypods="$(kubectl get pods  -o template -t "{{ len .items }}" "${kube_flags[@]}")" [ "$howmanypods" -eq 0 ]


func (c *connection) RemoveStreams(streams ...httpstream.Stream) { c.streamLock.Lock() for _, stream := range streams { <del> delete(c.streams, stream.Identifier()) </del> <ins> // It may be possible that the provided stream is nil if timed out. if stream != nil { delete(c.streams, stream.Identifier()) } </ins> } c.streamLock.Unlock() }


return nil, fmt.Errorf("failed to start container %q: %v", r.ContainerId, err) } <del> ds.performPlatformSpecificContainerForContainer(r.ContainerId) </del> return &runtimeapi.StartContainerResponse{}, nil }


import ( corev1 "k8s.io/api/core/v1" discovery "k8s.io/api/discovery/v1alpha1" <ins> apiequality "k8s.io/apimachinery/pkg/api/equality" </ins> "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" corev1client "k8s.io/client-go/kubernetes/typed/core/v1"


fs.BoolVar(&o.config.IPVS.StrictARP, "ipvs-strict-arp", o.config.IPVS.StrictARP, "Enable strict ARP by setting arp_ignore to 1 and arp_announce to 2") fs.BoolVar(&o.config.IPTables.MasqueradeAll, "masquerade-all", o.config.IPTables.MasqueradeAll, "If using the pure iptables proxy, SNAT all traffic sent via Service cluster IPs (this not commonly needed)") <del> fs.BoolVar(&o.config.EnableProfiling, "profiling", o.config.EnableProfiling, "If true enables profiling via web interface on /debug/pprof handler.") </del> <ins> fs.BoolVar(&o.config.EnableProfiling, "profiling", o.config.EnableProfiling, "If true enables profiling via web interface on /debug/pprof handler. This parameter is ignored if a config file is specified by --config.") </ins> fs.Float32Var(&o.config.ClientConnection.QPS, "kube-api-qps", o.config.ClientConnection.QPS, "QPS to use while talking with kubernetes apiserver") <del> fs.Var(&o.config.DetectLocalMode, "detect-local-mode", "Mode to use to detect local traffic") </del> <ins> fs.Var(&o.config.DetectLocalMode, "detect-local-mode", "Mode to use to detect local traffic. This parameter is ignored if a config file is specified by --config.") </ins> } // NewOptions returns initialized Options


package priorities import ( <ins> "os/exec" </ins> "reflect" "sort" "strconv"


opencontrail_kubernetes_tag: '$(echo "$OPENCONTRAIL_KUBERNETES_TAG" | sed -e "s/'/''/g")' opencontrail_public_subnet: '$(echo "$OPENCONTRAIL_PUBLIC_SUBNET" | sed -e "s/'/''/g")' e2e_storage_test_environment: '$(echo "$E2E_STORAGE_TEST_ENVIRONMENT" | sed -e "s/'/''/g")' <ins> enable_hostpath_provisioner: '$(echo "$ENABLE_HOSTPATH_PROVISIONER" | sed -e "s/'/''/g")' </ins> EOF cat <<EOF >/etc/salt/minion.d/log-level-debug.conf


<ins> {% if pillar.get('enable_node_autoscaler', '').lower() == 'true' %} </ins> {% set params = pillar['autoscaler_mig_config'] -%} { "kind": "Pod",


// newAgnhostPod returns a pod that uses the agnhost image. The image's binary supports various subcommands // that behave the same, no matter the underlying OS. func newAgnhostPod(name string, args ...string) *v1.Pod { <ins> zero := int64(0) </ins> return &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, Spec: v1.PodSpec{ <ins> TerminationGracePeriodSeconds: &zero, </ins> Containers: []v1.Container{ { Name:  "agnhost",


// NewDelayingQueueWithCustomClock constructs a new named workqueue // with ability to inject real or fake clock for testing purposes func NewDelayingQueueWithCustomClock(clock clock.Clock, name string) DelayingInterface { <ins> return newDelayingQueue(clock, NewNamed(name), name) } func newDelayingQueue(clock clock.Clock, q Interface, name string) *delayingType { </ins> ret := &delayingType{ <del> Interface:       NewNamed(name), </del> <ins> Interface:       q, </ins> clock:           clock, heartbeat:       clock.NewTicker(maxWait), stopCh:          make(chan struct{}),


t.Errorf("Service must be namespace scoped") } oldService := makeValidService() <del> newService := makeValidService() </del> <ins> oldService.Spec.Type = api.ServiceTypeLoadBalancer </ins> oldService.ResourceVersion = "4" <del> newService.ResourceVersion = "4" </del> <ins> oldService.Spec.SessionAffinity = "None" newService := oldService.DeepCopy() </ins> newService.Spec.SessionAffinity = "ClientIP" newService.Status = api.ServiceStatus{ LoadBalancer: api.LoadBalancerStatus{


// +listType=map // +listMapKey=name // +optional <del> Variables []Variable `json:"variables" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,7,rep,name=variables"` </del> <ins> Variables []Variable `json:"variables,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,7,rep,name=variables"` </ins> } type MatchCondition v1.MatchCondition


}, }, { <del> name: "StorageCapacity changed", </del> <ins> name: "TokenRequests invalidated", </ins> modify: func(new *storage.CSIDriver) { <del> new.Spec.StorageCapacity = &notStorageCapacity </del> <ins> new.Spec.TokenRequests = []storage.TokenRequest{{Audience: gcp}, {Audience: gcp}} </ins> }, }, { <del> name: "TokenRequests invalidated", </del> <ins> name: "invalid nil StorageCapacity", </ins> modify: func(new *storage.CSIDriver) { <del> new.Spec.TokenRequests = []storage.TokenRequest{{Audience: gcp}, {Audience: gcp}} </del> <ins> new.Spec.StorageCapacity = nil </ins> }, }, }


return iface.Name, nil } <del> func setUpAllInterfaces() error { interfaces, err := net.Interfaces() if err != nil { return err } for _, netIf := range interfaces { setUpInterface(netIf.Name) // ignore errors } return nil } </del> func setUpInterface(ifName string) error { glog.V(3).Infof("Enabling hairpin on interface %s", ifName) ifPath := path.Join(sysfsNetPath, ifName)


} } <del> // RecommendedConfigOverrideFlags is a convenience method to return recommended flag names prefixed with a string of your choosing func RecommendedConfigOverrideFlags(prefix string) ConfigOverrideFlags { return ConfigOverrideFlags{ AuthOverrideFlags:    RecommendedAuthOverrideFlags(prefix), ClusterOverrideFlags: RecommendedClusterOverrideFlags(prefix), ContextOverrideFlags: RecommendedContextOverrideFlags(prefix), CurrentContext: FlagInfo{prefix + FlagContext, "", "", "The name of the kubeconfig context to use"}, Timeout:        FlagInfo{prefix + FlagTimeout, "", "0", "The length of time to wait before giving up on a single server request. Non-zero values should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests."}, } } </del> // RecommendedContextOverrideFlags is a convenience method to return recommended flag names prefixed with a string of your choosing func RecommendedContextOverrideFlags(prefix string) ContextOverrideFlags { return ContextOverrideFlags{


"//vendor/golang.org/x/oauth2/google:go_default_library", "//vendor/google.golang.org/api/compute/v1:go_default_library", "//vendor/google.golang.org/api/dns/v1:go_default_library", <ins> "//vendor/google.golang.org/api/googleapi:go_default_library", </ins> "//vendor/gopkg.in/gcfg.v1:go_default_library", ], )