MounterSetUpTests(t, false) }) } <ins> func TestMounterSetUpWithFSGroup(t *testing.T) { fakeClient := fakeclient.NewSimpleClientset() plug, tmpDir := newTestPlugin(t, fakeClient, nil) defer os.RemoveAll(tmpDir) testCases := []struct { name        string accessModes []api.PersistentVolumeAccessMode readOnly    bool fsType      string setFsGroup  bool fsGroup     int64 }{ { name: "default fstype, with no fsgroup (should not apply fsgroup)", accessModes: []api.PersistentVolumeAccessMode{ api.ReadWriteOnce, }, readOnly: false, fsType:   "", }, { name: "default fstype  with fsgroup (should not apply fsgroup)", accessModes: []api.PersistentVolumeAccessMode{ api.ReadWriteOnce, }, readOnly:   false, fsType:     "", setFsGroup: true, fsGroup:    3000, }, { name: "fstype, fsgroup, RWM, ROM provided (should not apply fsgroup)", accessModes: []api.PersistentVolumeAccessMode{ api.ReadWriteMany, api.ReadOnlyMany, }, fsType:     "ext4", setFsGroup: true, fsGroup:    3000, }, { name: "fstype, fsgroup, RWO, but readOnly (should not apply fsgroup)", accessModes: []api.PersistentVolumeAccessMode{ api.ReadWriteOnce, }, readOnly:   true, fsType:     "ext4", setFsGroup: true, fsGroup:    3000, }, { name: "fstype, fsgroup, RWO provided (should apply fsgroup)", accessModes: []api.PersistentVolumeAccessMode{ api.ReadWriteOnce, }, fsType:     "ext4", setFsGroup: true, fsGroup:    3000, }, } for i, tc := range testCases { t.Logf("Running test %s", tc.name) volName := fmt.Sprintf("test-vol-%d", i) pv := makeTestPV("test-pv", 10, testDriver, volName) pv.Spec.AccessModes = tc.accessModes pvName := pv.GetName() spec := volume.NewSpecFromPersistentVolume(pv, tc.readOnly) if tc.fsType != "" { spec.PersistentVolume.Spec.CSI.FSType = tc.fsType } mounter, err := plug.NewMounter( spec, &api.Pod{ObjectMeta: meta.ObjectMeta{UID: testPodUID, Namespace: testns}}, volume.VolumeOptions{}, ) if err != nil { t.Fatalf("Failed to make a new Mounter: %v", err) } if mounter == nil { t.Fatal("failed to create CSI mounter") } csiMounter := mounter.(*csiMountMgr) csiMounter.csiClient = setupClient(t, true) attachID := getAttachmentName(csiMounter.volumeID, csiMounter.driverName, string(plug.host.GetNodeName())) attachment := makeTestAttachment(attachID, "test-node", pvName) _, err = csiMounter.k8s.StorageV1beta1().VolumeAttachments().Create(attachment) if err != nil { t.Errorf("failed to setup VolumeAttachment: %v", err) continue } // Mounter.SetUp() var fsGroupPtr *int64 if tc.setFsGroup { fsGroup := tc.fsGroup fsGroupPtr = &fsGroup } if err := csiMounter.SetUp(fsGroupPtr); err != nil { t.Fatalf("mounter.Setup failed: %v", err) } //Test the default value of file system type is not overridden if len(csiMounter.spec.PersistentVolume.Spec.CSI.FSType) != len(tc.fsType) { t.Errorf("file system type was overridden by type %s", csiMounter.spec.PersistentVolume.Spec.CSI.FSType) } // ensure call went all the way pubs := csiMounter.csiClient.(*fakeCsiDriverClient).nodeClient.GetNodePublishedVolumes() if pubs[csiMounter.volumeID].Path != csiMounter.GetPath() { t.Error("csi server may not have received NodePublishVolume call") } } } </ins> func TestUnmounterTeardown(t *testing.T) { plug, tmpDir := newTestPlugin(t, nil, nil)


package events <del> import ( "k8s.io/api/core/v1" clientv1 "k8s.io/api/core/v1" ) </del> const ( // Container event reason list CreatedContainer        = "Created"


gomega.Expect(stdout).To(gomega.Equal(mountName), msg) } else { // We *expect* cat to return error here <del> gomega.Expect(err).To(gomega.HaveOccurred(), msg) </del> <ins> framework.ExpectError(err, msg) </ins> } } }


package net import ( <ins> "crypto/tls" </ins> "net" "net/http" "net/url" "os" "reflect" "testing" <ins> "k8s.io/kubernetes/pkg/util/sets" </ins> ) <ins> func TestCloneTLSConfig(t *testing.T) { expected := sets.NewString( // These fields are copied in CloneTLSConfig "Rand", "Time", "Certificates", "RootCAs", "NextProtos", "ServerName", "InsecureSkipVerify", "CipherSuites", "PreferServerCipherSuites", "MinVersion", "MaxVersion", "CurvePreferences", "NameToCertificate", "GetCertificate", "ClientAuth", "ClientCAs", "ClientSessionCache", // These fields are not copied "SessionTicketsDisabled", "SessionTicketKey", // These fields are unexported "serverInitOnce", "mutex", "sessionTicketKeys", ) fields := sets.NewString() structType := reflect.TypeOf(tls.Config{}) for i := 0; i < structType.NumField(); i++ { fields.Insert(structType.Field(i).Name) } if missing := expected.Difference(fields); len(missing) > 0 { t.Errorf("Expected fields that were not seen in http.Transport: %v", missing.List()) } if extra := fields.Difference(expected); len(extra) > 0 { t.Errorf("New fields seen in http.Transport: %vnAdd to CopyClientTLSConfig if client-relevant, then add to expected list in TestCopyClientTLSConfig", extra.List()) } } </ins> func TestGetClientIP(t *testing.T) { ipString := "10.0.0.1" ip := net.ParseIP(ipString)


vmPowerStateStopped      = "stopped" vmPowerStateDeallocated  = "deallocated" vmPowerStateDeallocating = "deallocating" <ins> // nodeNameEnvironmentName is the environment variable name for getting node name. // It is only used for out-of-tree cloud provider. nodeNameEnvironmentName = "NODE_NAME" </ins> ) var (


"containers": [ { "name": "kubernetes-pause", <del> "image": "gcr.io/google_containers/pause-amd64:3.0" </del> <ins> "image": "gcr.io/google_containers/pause-amd64:3.1" </ins> } ], "restartPolicy": "Never",


registry = "k8s.gcr.io/build-image", repository = "debian-iptables", # Ensure the digests above are updated to match a new tag <del> tag = "buster-v1.4.0",  # ignored, but kept here for documentation </del> <ins> tag = "buster-v1.5.0",  # ignored, but kept here for documentation </ins> ) def etcd_tarballs():


if err != nil { return probe.Unknown, err } <del> if strings.ToLower(string(data)) != defaultHealthyOutput { </del> <ins> if !strings.HasPrefix(strings.ToLower(string(data)), defaultHealthyOutput) { </ins> return probe.Failure, nil } return probe.Success, nil


// Otherwise we will return an error. func findSecurityGroupForInstance(instance *ec2.Instance, taggedSecurityGroups map[string]*ec2.SecurityGroup) (*ec2.GroupIdentifier, error) { instanceID := aws.StringValue(instance.InstanceId) <del> var best *ec2.GroupIdentifier </del> <ins> var tagged []*ec2.GroupIdentifier var untagged []*ec2.GroupIdentifier </ins> for _, group := range instance.SecurityGroups { groupID := aws.StringValue(group.GroupId) if groupID == "" { glog.Warningf("Ignoring security group without id for instance %q: %v", instanceID, group) continue } <del> if best == nil { best = group continue </del> <ins> _, isTagged := taggedSecurityGroups[groupID] if isTagged { tagged = append(tagged, group) } else { untagged = append(untagged, group) </ins> } <ins> } </ins> <del> _, bestIsTagged := taggedSecurityGroups[*best.GroupId] _, groupIsTagged := taggedSecurityGroups[groupID] if bestIsTagged && !groupIsTagged { // best is still best } else if groupIsTagged && !bestIsTagged { best = group } else { // We create instances with one SG // If users create multiple SGs, they must tag one of them as being k8s owned return nil, fmt.Errorf("Multiple security groups found for instance (%s); ensure the k8s security group is tagged", instanceID) </del> <ins> if len(tagged) > 0 { // We create instances with one SG // If users create multiple SGs, they must tag one of them as being k8s owned if len(tagged) != 1 { return nil, fmt.Errorf("Multiple tagged security groups found for instance %s; ensure only the k8s security group is tagged", instanceID) </ins> } <ins> return tagged[0], nil </ins> } <del> if best == nil { glog.Warningf("No security group found for instance %q", instanceID) </del> <ins> if len(untagged) > 0 { // For back-compat, we will allow a single untagged SG if len(untagged) != 1 { return nil, fmt.Errorf("Multiple untagged security groups found for instance %s; ensure the k8s security group is tagged", instanceID) } return untagged[0], nil </ins> } <del> return best, nil </del> <ins> glog.Warningf("No security group found for instance %q", instanceID) return nil, nil </ins> } // Return all the security groups that are tagged as being part of our cluster


} } <del> func TestSetDefaultReplicationControllerImagePullPolicy(t *testing.T) { containersWithoutPullPolicy, _ := json.Marshal([]map[string]interface{}{ { "name":  "install", "image": "busybox:latest", }, }) </del> <ins> type InitContainerValidator func(got, expected *v1.Container) error </ins> <del> containersWithPullPolicy, _ := json.Marshal([]map[string]interface{}{ { "name":            "install", "imagePullPolicy": "IfNotPresent", }, }) </del> <ins> func TestSetDefaultReplicationControllerInitContainers(t *testing.T) { assertEnvFieldRef := func(got, expected *v1.Container) error { if len(got.Env) != len(expected.Env) { return fmt.Errorf("different number of env: got <%v>, expected <%v>", len(got.Env), len(expected.Env)) } for j := range got.Env { ge := &got.Env[j] ee := &expected.Env[j] if ge.Name != ee.Name { return fmt.Errorf("different name of env: got <%v>, expected <%v>", ge.Name, ee.Name) } if ge.ValueFrom.FieldRef.APIVersion != ee.ValueFrom.FieldRef.APIVersion { return fmt.Errorf("different api version of FieldRef <%v>: got <%v>, expected <%v>", ge.Name, ge.ValueFrom.FieldRef.APIVersion, ee.ValueFrom.FieldRef.APIVersion) } } return nil } assertImagePullPolicy := func(got, expected *v1.Container) error { if got.ImagePullPolicy != expected.ImagePullPolicy { return fmt.Errorf("different image pull poicy: got <%v>, expected <%v>", got.ImagePullPolicy, expected.ImagePullPolicy) } return nil } assertContainerPort := func(got, expected *v1.Container) error { if len(got.Ports) != len(expected.Ports) { return fmt.Errorf("different number of ports: got <%v>, expected <%v>", len(got.Ports), len(expected.Ports)) } for i := range got.Ports { gp := &got.Ports[i] ep := &expected.Ports[i] if gp.Name != ep.Name { return fmt.Errorf("different name of port: got <%v>, expected <%v>", gp.Name, ep.Name) } if gp.Protocol != ep.Protocol { return fmt.Errorf("different port protocol <%v>: got <%v>, expected <%v>", gp.Name, gp.Protocol, ep.Protocol) } } return nil } assertResource := func(got, expected *v1.Container) error { if len(got.Resources.Limits) != len(expected.Resources.Limits) { return fmt.Errorf("different number of resources.Limits: got <%v>, expected <%v>", len(got.Resources.Limits), (expected.Resources.Limits)) } for k, v := range got.Resources.Limits { if ev, found := expected.Resources.Limits[v1.ResourceName(k)]; !found { return fmt.Errorf("failed to find resource <%v> in expected resources.Limits.", k) } else { if ev.Value() != v.Value() { return fmt.Errorf("different resource.Limits: got <%v>, expected <%v>.", v.Value(), ev.Value()) } } } if len(got.Resources.Requests) != len(expected.Resources.Requests) { return fmt.Errorf("different number of resources.Requests: got <%v>, expected <%v>", len(got.Resources.Requests), (expected.Resources.Requests)) } for k, v := range got.Resources.Requests { if ev, found := expected.Resources.Requests[v1.ResourceName(k)]; !found { return fmt.Errorf("failed to find resource <%v> in expected resources.Requests.", k) } else { if ev.Value() != v.Value() { return fmt.Errorf("different resource.Requests: got <%v>, expected <%v>.", v.Value(), ev.Value()) } } } return nil } assertProb := func(got, expected *v1.Container) error { // Assert LivenessProbe if got.LivenessProbe.Handler.HTTPGet.Path != expected.LivenessProbe.Handler.HTTPGet.Path || got.LivenessProbe.Handler.HTTPGet.Scheme != expected.LivenessProbe.Handler.HTTPGet.Scheme || got.LivenessProbe.FailureThreshold != expected.LivenessProbe.FailureThreshold || got.LivenessProbe.SuccessThreshold != expected.LivenessProbe.SuccessThreshold || got.LivenessProbe.PeriodSeconds != expected.LivenessProbe.PeriodSeconds || got.LivenessProbe.TimeoutSeconds != expected.LivenessProbe.TimeoutSeconds { return fmt.Errorf("different LivenessProbe: got <%v>, expected <%v>", got.LivenessProbe, expected.LivenessProbe) } // Assert ReadinessProbe if got.ReadinessProbe.Handler.HTTPGet.Path != expected.ReadinessProbe.Handler.HTTPGet.Path || got.ReadinessProbe.Handler.HTTPGet.Scheme != expected.ReadinessProbe.Handler.HTTPGet.Scheme || got.ReadinessProbe.FailureThreshold != expected.ReadinessProbe.FailureThreshold || got.ReadinessProbe.SuccessThreshold != expected.ReadinessProbe.SuccessThreshold || got.ReadinessProbe.PeriodSeconds != expected.ReadinessProbe.PeriodSeconds || got.ReadinessProbe.TimeoutSeconds != expected.ReadinessProbe.TimeoutSeconds { return fmt.Errorf("different ReadinessProbe: got <%v>, expected <%v>", got.ReadinessProbe, expected.ReadinessProbe) } return nil } assertLifeCycle := func(got, expected *v1.Container) error { if got.Lifecycle.PostStart.HTTPGet.Path != expected.Lifecycle.PostStart.HTTPGet.Path || got.Lifecycle.PostStart.HTTPGet.Scheme != expected.Lifecycle.PostStart.HTTPGet.Scheme { return fmt.Errorf("different LifeCycle: got <%v>, expected <%v>", got.Lifecycle, expected.Lifecycle) } return nil } cpu, _ := resource.ParseQuantity("100Gi") mem, _ := resource.ParseQuantity("100Mi") </ins> tests := []struct { <del> rc               v1.ReplicationController expectPullPolicy v1.PullPolicy </del> <ins> name       string rc         v1.ReplicationController expected   []v1.Container validators []InitContainerValidator </ins> }{ { <ins> name: "imagePullIPolicy", rc: v1.ReplicationController{ Spec: v1.ReplicationControllerSpec{ Template: &v1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ "pod.beta.kubernetes.io/init-containers": ` [ { "name": "install", "image": "busybox" } ]`, }, }, }, }, }, expected: []v1.Container{ { ImagePullPolicy: v1.PullAlways, }, }, validators: []InitContainerValidator{assertImagePullPolicy}, }, { name: "FieldRef", rc: v1.ReplicationController{ Spec: v1.ReplicationControllerSpec{ Template: &v1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ "pod.beta.kubernetes.io/init-containers": ` [ { "name": "fun", "image": "alpine", "env": [ { "name": "MY_POD_IP", "valueFrom": { "fieldRef": { "apiVersion": "", "fieldPath": "status.podIP" } } } ] } ]`, }, }, }, }, }, expected: []v1.Container{ { Env: []v1.EnvVar{ { Name: "MY_POD_IP", ValueFrom: &v1.EnvVarSource{ FieldRef: &v1.ObjectFieldSelector{ APIVersion: "v1", FieldPath:  "status.podIP", }, }, }, }, }, }, validators: []InitContainerValidator{assertEnvFieldRef}, }, { name: "ContainerPort", </ins> rc: v1.ReplicationController{ Spec: v1.ReplicationControllerSpec{ Template: &v1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ <del> "pod.beta.kubernetes.io/init-containers": string(containersWithoutPullPolicy), </del> <ins> "pod.beta.kubernetes.io/init-containers": ` [ { "name": "fun", "image": "alpine", "ports": [ { "name": "default" } ] } ]`, </ins> }, }, }, }, }, <del> expectPullPolicy: v1.PullAlways, </del> <ins> expected: []v1.Container{ { Ports: []v1.ContainerPort{ { Name:     "default", Protocol: v1.ProtocolTCP, }, }, }, }, validators: []InitContainerValidator{assertContainerPort}, </ins> }, { <ins> name: "Resources", </ins> rc: v1.ReplicationController{ Spec: v1.ReplicationControllerSpec{ Template: &v1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ <del> "pod.beta.kubernetes.io/init-containers": string(containersWithPullPolicy), </del> <ins> "pod.beta.kubernetes.io/init-containers": ` [ { "name": "fun", "image": "alpine", "resources": { "limits": { "cpu": "100Gi", "memory": "100Mi" }, "requests": { "cpu": "100Gi", "memory": "100Mi" } } } ]`, </ins> }, }, }, }, }, <del> expectPullPolicy: v1.PullIfNotPresent, </del> <ins> expected: []v1.Container{ { Resources: v1.ResourceRequirements{ Limits: v1.ResourceList{ v1.ResourceCPU:    cpu, v1.ResourceMemory: mem, }, Requests: v1.ResourceList{ v1.ResourceCPU:    cpu, v1.ResourceMemory: mem, }, }, }, }, validators: []InitContainerValidator{assertResource}, }, { name: "Prob", rc: v1.ReplicationController{ Spec: v1.ReplicationControllerSpec{ Template: &v1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ "pod.beta.kubernetes.io/init-containers": ` [ { "name": "fun", "image": "alpine", "livenessProbe": { "httpGet": { "host": "localhost" } }, "readinessProbe": { "httpGet": { "host": "localhost" } } } ]`, }, }, }, }, }, expected: []v1.Container{ { LivenessProbe: &v1.Probe{ Handler: v1.Handler{ HTTPGet: &v1.HTTPGetAction{ Path:   "/", Scheme: v1.URISchemeHTTP, }, }, TimeoutSeconds:   1, PeriodSeconds:    10, SuccessThreshold: 1, FailureThreshold: 3, }, ReadinessProbe: &v1.Probe{ Handler: v1.Handler{ HTTPGet: &v1.HTTPGetAction{ Path:   "/", Scheme: v1.URISchemeHTTP, }, }, TimeoutSeconds:   1, PeriodSeconds:    10, SuccessThreshold: 1, FailureThreshold: 3, }, }, }, validators: []InitContainerValidator{assertProb}, }, { name: "LifeCycle", rc: v1.ReplicationController{ Spec: v1.ReplicationControllerSpec{ Template: &v1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ "pod.beta.kubernetes.io/init-containers": ` [ { "name": "fun", "image": "alpine", "lifecycle": { "postStart": { "httpGet": { "host": "localhost" } }, "preStop": { "httpGet": { "host": "localhost" } } } } ]`, }, }, }, }, }, expected: []v1.Container{ { Lifecycle: &v1.Lifecycle{ PostStart: &v1.Handler{ HTTPGet: &v1.HTTPGetAction{ Path:   "/", Scheme: v1.URISchemeHTTP, }, }, PreStop: &v1.Handler{ HTTPGet: &v1.HTTPGetAction{ Path:   "/", Scheme: v1.URISchemeHTTP, }, }, }, }, }, validators: []InitContainerValidator{assertLifeCycle}, </ins> }, } <ins> assertInitContainers := func(got, expected []v1.Container, validators []InitContainerValidator) error { if len(got) != len(expected) { return fmt.Errorf("different number of init container: got <%d>, expected <%d>", len(got), len(expected)) } for i := range got { g := &got[i] e := &expected[i] for _, validator := range validators { if err := validator(g, e); err != nil { return err } } } return nil } </ins> for _, test := range tests { rc := &test.rc obj2 := roundTrip(t, runtime.Object(rc))


} if latency := time.Since(now); latency > longThrottleLatency { <del> klog.V(4).Infof("Throttling request took %v, request: %s:%s", latency, r.verb, r.URL().String()) </del> <ins> klog.V(3).Infof("Throttling request took %v, request: %s:%s", latency, r.verb, r.URL().String()) </ins> } return err


hash := hash(nodeUpdate.name()) select { case <-stopCh: <ins> tc.nodeUpdateQueue.Done(item) </ins> break case tc.nodeUpdateChannels[hash%workers] <- nodeUpdate: } <ins> tc.nodeUpdateQueue.Done(item) </ins> } }(stopCh)


framework.ExpectNoError(err, "failed to see %v event", watch.Deleted) }) <del> ginkgo.It("should validate Deployment Status endpoints", func() { </del> <ins> /* Release: v1.22 Testname: Deployment, status sub-resource 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. */ framework.ConformanceIt("should validate Deployment Status endpoints", func() { </ins> dClient := c.AppsV1().Deployments(ns) dName := "test-deployment-" + utilrand.String(5) labelSelector := "e2e=testing"


cmd.Flags().BoolVar(&options.All, "all", false, "select all resources in the namespace of the specified resource types") cmd.Flags().StringVarP(&options.Selector, "selector", "l", "", "Selector (label query) to filter on") cmd.Flags().StringVarP(&options.ContainerSelector, "containers", "c", "*", "The names of containers in the selected pod templates to change, all containers are selected by default - may use wildcards") <del> cmd.Flags().BoolVar(&options.Local, "local", false, "If true, set resources will NOT contact api-server but run locally.") </del> cmdutil.AddDryRunFlag(cmd) cmdutil.AddRecordFlag(cmd) cmd.Flags().StringVar(&options.Limits, "limits", options.Limits, "The resource requirement requests for this container.  For example, 'cpu=100m,memory=256Mi'.  Note that server side components may assign requests depending on the server configuration, such as limit ranges.")


) apiserverRequestConcurrencyInUse = compbasemetrics.NewGaugeVec( &compbasemetrics.GaugeOpts{ <del> Namespace:         namespace, Subsystem:         subsystem, Name:              "request_concurrency_in_use", Help:              "Concurrency (number of seats) occupied by the currently executing (initial stage for a WATCH, any stage otherwise) requests in the API Priority and Fairness subsystem", DeprecatedVersion: "1.28.0", </del> <ins> Namespace: namespace, Subsystem: subsystem, Name:      "request_concurrency_in_use", Help:      "Concurrency (number of seats) occupied by the currently executing (initial stage for a WATCH, any stage otherwise) requests in the API Priority and Fairness subsystem", // Remove this metric once all suppported releases have the equal current_executing_seats metric DeprecatedVersion: "1.31.0", </ins> StabilityLevel:    compbasemetrics.ALPHA, }, []string{priorityLevel, flowSchema},


TestDynamicProvisioning(input.testCase, input.cs, input.pvc, input.sc) }) <del> It("should provision storage with non-default reclaim policy Retain", func() { retain := v1.PersistentVolumeReclaimRetain input.sc.ReclaimPolicy = &retain pv := TestDynamicProvisioning(input.testCase, input.cs, input.pvc, input.sc) By(fmt.Sprintf("waiting for the provisioned PV %q to enter phase %s", pv.Name, v1.VolumeReleased)) framework.ExpectNoError(framework.WaitForPersistentVolumePhase(v1.VolumeReleased, input.cs, pv.Name, 1*time.Second, 30*time.Second)) By(fmt.Sprintf("deleting the PV %q", pv.Name)) framework.ExpectNoError(framework.DeletePersistentVolume(input.cs, pv.Name), "Failed to delete PV ", pv.Name) framework.ExpectNoError(framework.WaitForPersistentVolumeDeleted(input.cs, pv.Name, 1*time.Second, 30*time.Second)) }) </del> It("should create and delete block persistent volumes [Feature:BlockVolume]", func() { if !input.dInfo.IsBlockSupported { framework.Skipf("Driver %q does not support BlockVolume - skipping", input.dInfo.Name)


startLocalStreamingServer bool // containerCleanupInfos maps container IDs to the `containerCleanupInfo` structs <del> // needed to clean up after containers have been started or removed. </del> <ins> // needed to clean up after containers have been removed. </ins> // (see `applyPlatformSpecificDockerConfig` and `performPlatformSpecificContainerCleanup` // methods for more info). containerCleanupInfos map[string]*containerCleanupInfo


serviceName := "svc-itp" ns := f.Namespace.Name <del> servicePort := 8000 </del> <ins> servicePort := 80 // If the pod can't bind to this port, it will fail to start, and it will fail the test, // because is using hostNetwork. Using a not common port will reduce this possibility. endpointPort := 10180 </ins> ginkgo.By("creating a TCP service " + serviceName + " with type=ClusterIP and internalTrafficPolicy=Local in namespace " + ns) local := v1.ServiceInternalTrafficPolicyLocal jig := e2eservice.NewTestJig(cs, ns, serviceName) svc, err := jig.CreateTCPService(func(svc *v1.Service) { svc.Spec.Ports = []v1.ServicePort{ <del> {Port: 8000, Name: "http", Protocol: v1.ProtocolTCP, TargetPort: intstr.FromInt(8000)}, </del> <ins> {Port: 80, Name: "http", Protocol: v1.ProtocolTCP, TargetPort: intstr.FromInt(endpointPort)}, </ins> } svc.Spec.InternalTrafficPolicy = &local }) framework.ExpectNoError(err) ginkgo.By("Creating 1 webserver pod to be part of the TCP service") <del> webserverPod0 := e2epod.NewAgnhostPod(ns, "echo-hostname-0", nil, nil, nil, "netexec", "--http-port", strconv.Itoa(servicePort)) </del> <ins> webserverPod0 := e2epod.NewAgnhostPod(ns, "echo-hostname-0", nil, nil, nil, "netexec", "--http-port", strconv.Itoa(endpointPort)) </ins> webserverPod0.Labels = jig.Labels webserverPod0.Spec.HostNetwork = true e2epod.SetNodeSelection(&webserverPod0.Spec, e2epod.NodeSelection{Name: node0.Name})


#   standalone     - Heapster only. Metrics available via Heapster REST API. ENABLE_CLUSTER_MONITORING="${KUBE_ENABLE_CLUSTER_MONITORING:-influxdb}" <ins> # Historically fluentd was a manifest pod and then was migrated to DaemonSet. # To avoid situation during cluster upgrade when there are two instances # of fluentd running on a node, kubelet need to mark node on which # fluentd is not running as a manifest pod with appropriate label. # TODO(piosz): remove this in 1.8 NODE_LABELS="${KUBE_NODE_LABELS:-alpha.kubernetes.io/fluentd-ds-ready=true}" </ins> # Optional: Enable node logging. ENABLE_NODE_LOGGING="${KUBE_ENABLE_NODE_LOGGING:-true}" LOGGING_DESTINATION="${KUBE_LOGGING_DESTINATION:-gcp}" # options: elasticsearch, gcp


func setSandboxResources(hc *dockercontainer.HostConfig) { hc.Resources = dockercontainer.Resources{ <del> MemorySwap: -1, </del> <ins> MemorySwap: dockertools.DefaultMemorySwap(), </ins> CPUShares:  defaultSandboxCPUshares, // Use docker's default cpu quota/period. }


Labels: labels, }, Spec: api.PodSpec{ <del> Containers: []api.Container{c}, </del> <ins> Containers:                    []api.Container{c}, TerminationGracePeriodSeconds: &gracePeriod, </ins> }, }, },


"k8s.io/kubernetes/pkg/client/cache" client "k8s.io/kubernetes/pkg/client/unversioned" "k8s.io/kubernetes/pkg/controller" <ins> "k8s.io/kubernetes/pkg/runtime" </ins> "k8s.io/kubernetes/pkg/securitycontext" <ins> utiltesting "k8s.io/kubernetes/pkg/util/testing" </ins> ) var (


## Requirements 1. Docker, using one of the following configurations: <del> * **macOS** Install Docker for Mac. See installation instructions [here](https://docs.docker.com/docker-for-mac/). </del> <ins> * **macOS** Install Docker for Mac. See installation instructions [here](https://docs.docker.com/desktop/install/mac-install/). </ins> **Note**: You will want to set the Docker VM to have at least 8GB of initial memory or building will likely fail. (See: [#11852]( http://issue.k8s.io/11852)). * **Linux with local Docker**  Install Docker according to the [instructions](https://docs.docker.com/installation/#installation) for your OS. * **Windows with Docker Desktop WSL2 backend**  Install Docker according to the [instructions](https://docs.docker.com/docker-for-windows/wsl-tech-preview/). Be sure to store your sources in the local Linux file system, not the Windows remote mount at `/mnt/c`.


t.objects[gvr][namespacedName] = obj for _, w := range t.getWatches(gvr, ns) { <del> w.Add(obj) </del> <ins> // To avoid the object from being accidentally modified by watcher w.Add(obj.DeepCopyObject()) </ins> } return nil


) func (c *FakeEvictions) Evict(eviction *policy.Eviction) error { <del> action := core.GetActionImpl{} action.Verb = "post" </del> <ins> action := core.CreateActionImpl{} action.Verb = "create" </ins> action.Namespace = c.ns action.Resource = schema.GroupVersionResource{Group: "", Version: "v1", Resource: "pods"} action.Subresource = "eviction" <del> action.Name = eviction.Name </del> <ins> action.Object = eviction </ins> _, err := c.Fake.Invokes(action, eviction) return err }


name = "all-srcs", srcs = [ ":package-srcs", <ins> "//pkg/kubelet/apis/kubeletconfig/fuzzer:all-srcs", </ins> "//pkg/kubelet/apis/kubeletconfig/scheme:all-srcs", "//pkg/kubelet/apis/kubeletconfig/v1alpha1:all-srcs", "//pkg/kubelet/apis/kubeletconfig/validation:all-srcs",


current-release-pr current-replicas daemonset-lookup-cache-size <ins> data-dir </ins> default-container-cpu-limit default-container-mem-limit delay-shutdown


"golang.org/x/net/websocket" <ins> "encoding/json" </ins> v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" <ins> "k8s.io/apimachinery/pkg/runtime/schema" </ins> "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/util/uuid" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/apimachinery/pkg/watch" <ins> "k8s.io/client-go/dynamic" </ins> "k8s.io/client-go/tools/cache" watchtools "k8s.io/client-go/tools/watch" podutil "k8s.io/kubernetes/pkg/api/v1/pod"


return selector.PodSelectorMatches } <del> // NodeMatchesNodeSelectorTerms checks if a node's labels satisfy a list of node selector terms, </del> <ins> // nodeMatchesNodeSelectorTerms checks if a node's labels satisfy a list of node selector terms, </ins> // terms are ORed, and an emtpy a list of terms will match nothing. <del> func NodeMatchesNodeSelectorTerms(node *api.Node, nodeSelectorTerms []api.NodeSelectorTerm) bool { </del> <ins> func nodeMatchesNodeSelectorTerms(node *api.Node, nodeSelectorTerms []api.NodeSelectorTerm) bool { </ins> for _, req := range nodeSelectorTerms { nodeSelector, err := api.NodeSelectorRequirementsAsSelector(req.MatchExpressions) if err != nil {


if want == "" { want = "<nil>" } <del> if got := fmt.Sprintf("%v", err); got != want { </del> <ins> if got := fmt.Sprintf("%v", err); !strings.Contains(got, want) { </ins> t.Errorf("wrong error for message %q: want=%q, got=%q", test.message, want, got) } }


apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" <ins> "k8s.io/apimachinery/pkg/util/uuid" </ins> "k8s.io/apimachinery/pkg/util/wait" "k8s.io/kubernetes/test/e2e/framework" e2epod "k8s.io/kubernetes/test/e2e/framework/pod" imageutils "k8s.io/kubernetes/test/utils/image" "github.com/onsi/ginkgo" <ins> "k8s.io/apimachinery/pkg/types" </ins> ) func extinguish(f *framework.Framework, totalNS int, maxAllowedAfterDel int, maxSeconds int) {


cloud: gce EOF <ins> DOCKER_OPTS="" if [[ -n "${EXTRA_DOCKER_OPTS-}" ]]; then DOCKER_OPTS="${EXTRA_DOCKER_OPTS}" fi </ins> # Decide if enable the cache <del> if [[ "${ENABLE_DOCKER_REGISTRY_CACHE}" == "true" ]]; then </del> <ins> if [[ "${ENABLE_DOCKER_REGISTRY_CACHE}" == "true" ]]; then </ins> REGION=$(echo "${ZONE}" | cut -f 1,2 -d -) echo "Enable docker registry cache at region: " $REGION <del> DOCKER_OPTS="--registry-mirror="https://${REGION}.docker-cache.clustermaster.net"" </del> <ins> DOCKER_OPTS="${DOCKER_OPTS} --registry-mirror='https://${REGION}.docker-cache.clustermaster.net'" fi </ins> <del> cat <<EOF >>/etc/salt/minion.d/grains.conf </del> <ins> if [[ -n "{DOCKER_OPTS}" ]]; then cat <<EOF >>/etc/salt/minion.d/grains.conf </ins> docker_opts: $DOCKER_OPTS EOF fi


} func TestValidateNamespaceStatusUpdate(t *testing.T) { <ins> now := util.Now() </ins> tests := []struct { oldNamespace api.Namespace namespace    api.Namespace valid        bool }{ <del> {api.Namespace{}, api.Namespace{}, true}, </del> <ins> {api.Namespace{}, api.Namespace{ Status: api.NamespaceStatus{ Phase: api.NamespaceActive, }, }, true}, </ins> {api.Namespace{ ObjectMeta: api.ObjectMeta{ Name: "foo"}}, api.Namespace{ ObjectMeta: api.ObjectMeta{ <del> Name: "foo"}, </del> <ins> Name:              "foo", DeletionTimestamp: &now}, </ins> Status: api.NamespaceStatus{ Phase: api.NamespaceTerminating, },


nodePorts[key] = true } <ins> // Check for duplicate TargetPort portsPath = specPath.Child("ports") targetPorts := make(map[api.ServicePort]bool) for i, port := range service.Spec.Ports { if (port.TargetPort.Type == intstr.Int && port.TargetPort.IntVal == 0) || (port.TargetPort.Type == intstr.String && port.TargetPort.StrVal == "") { continue } portPath := portsPath.Index(i) key := api.ServicePort{Protocol: port.Protocol, TargetPort: port.TargetPort} _, found := targetPorts[key] if found { allErrs = append(allErrs, field.Duplicate(portPath.Child("targetPort"), port.TargetPort)) } targetPorts[key] = true } </ins> // Validate SourceRange field and annotation _, ok := service.Annotations[api.AnnotationLoadBalancerSourceRangesKey] if len(service.Spec.LoadBalancerSourceRanges) > 0 || ok {


"name":        "The name of this port. All ports in an EndpointSlice must have a unique name. If the EndpointSlice is dervied from a Kubernetes service, this corresponds to the Service.ports[].name. Name must either be an empty string or pass DNS_LABEL validation: * must be no more than 63 characters long. * must consist of lower case alphanumeric characters or '-'. * must start and end with an alphanumeric character. Default is empty string.", "protocol":    "The IP protocol for this port. Must be UDP, TCP, or SCTP. Default is TCP.", "port":        "The port number of the endpoint. If this is not specified, ports are not restricted and must be interpreted in the context of the specific consumer.", <del> "appProtocol": "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> "appProtocol": "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> } func (EndpointPort) SwaggerDoc() map[string]string {


"reflect" "sort" "testing" <ins> "time" </ins> "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require"


<del> { "apiVersion": "apidiscovery.k8s.io/v2beta1", "items": [ { "metadata": { "creationTimestamp": null, "name": "apiregistration.k8s.io" }, "versions": [ { "freshness": "Current", "resources": [ { "categories": [ "api-extensions" ], "resource": "apiservices", "responseKind": { "group": "", "kind": "APIService", "version": "" }, "scope": "Cluster", "singularResource": "apiservice", "subresources": [ { "responseKind": { "group": "", "kind": "APIService", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1" } ] }, { "metadata": { "creationTimestamp": null, "name": "apps" }, "versions": [ { "freshness": "Current", "resources": [ { "resource": "controllerrevisions", "responseKind": { "group": "", "kind": "ControllerRevision", "version": "" }, "scope": "Namespaced", "singularResource": "controllerrevision", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "categories": [ "all" ], "resource": "daemonsets", "responseKind": { "group": "", "kind": "DaemonSet", "version": "" }, "scope": "Namespaced", "shortNames": [ "ds" ], "singularResource": "daemonset", "subresources": [ { "responseKind": { "group": "", "kind": "DaemonSet", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "categories": [ "all" ], "resource": "deployments", "responseKind": { "group": "", "kind": "Deployment", "version": "" }, "scope": "Namespaced", "shortNames": [ "deploy" ], "singularResource": "deployment", "subresources": [ { "responseKind": { "group": "autoscaling", "kind": "Scale", "version": "v1" }, "subresource": "scale", "verbs": [ "get", "patch", "update" ] }, { "responseKind": { "group": "", "kind": "Deployment", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "categories": [ "all" ], "resource": "replicasets", "responseKind": { "group": "", "kind": "ReplicaSet", "version": "" }, "scope": "Namespaced", "shortNames": [ "rs" ], "singularResource": "replicaset", "subresources": [ { "responseKind": { "group": "autoscaling", "kind": "Scale", "version": "v1" }, "subresource": "scale", "verbs": [ "get", "patch", "update" ] }, { "responseKind": { "group": "", "kind": "ReplicaSet", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "categories": [ "all" ], "resource": "statefulsets", "responseKind": { "group": "", "kind": "StatefulSet", "version": "" }, "scope": "Namespaced", "shortNames": [ "sts" ], "singularResource": "statefulset", "subresources": [ { "responseKind": { "group": "autoscaling", "kind": "Scale", "version": "v1" }, "subresource": "scale", "verbs": [ "get", "patch", "update" ] }, { "responseKind": { "group": "", "kind": "StatefulSet", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1" } ] }, { "metadata": { "creationTimestamp": null, "name": "events.k8s.io" }, "versions": [ { "freshness": "Current", "resources": [ { "resource": "events", "responseKind": { "group": "", "kind": "Event", "version": "" }, "scope": "Namespaced", "shortNames": [ "ev" ], "singularResource": "event", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1" } ] }, { "metadata": { "creationTimestamp": null, "name": "authentication.k8s.io" }, "versions": [ { "freshness": "Current", "resources": [ { "resource": "selfsubjectreviews", "responseKind": { "group": "", "kind": "SelfSubjectReview", "version": "" }, "scope": "Cluster", "singularResource": "selfsubjectreview", "verbs": [ "create" ] }, { "resource": "tokenreviews", "responseKind": { "group": "", "kind": "TokenReview", "version": "" }, "scope": "Cluster", "singularResource": "tokenreview", "verbs": [ "create" ] } ], "version": "v1" }, { "freshness": "Current", "resources": [ { "resource": "selfsubjectreviews", "responseKind": { "group": "", "kind": "SelfSubjectReview", "version": "" }, "scope": "Cluster", "singularResource": "selfsubjectreview", "verbs": [ "create" ] } ], "version": "v1beta1" }, { "freshness": "Current", "resources": [ { "resource": "selfsubjectreviews", "responseKind": { "group": "", "kind": "SelfSubjectReview", "version": "" }, "scope": "Cluster", "singularResource": "selfsubjectreview", "verbs": [ "create" ] } ], "version": "v1alpha1" } ] }, { "metadata": { "creationTimestamp": null, "name": "authorization.k8s.io" }, "versions": [ { "freshness": "Current", "resources": [ { "resource": "localsubjectaccessreviews", "responseKind": { "group": "", "kind": "LocalSubjectAccessReview", "version": "" }, "scope": "Namespaced", "singularResource": "localsubjectaccessreview", "verbs": [ "create" ] }, { "resource": "selfsubjectaccessreviews", "responseKind": { "group": "", "kind": "SelfSubjectAccessReview", "version": "" }, "scope": "Cluster", "singularResource": "selfsubjectaccessreview", "verbs": [ "create" ] }, { "resource": "selfsubjectrulesreviews", "responseKind": { "group": "", "kind": "SelfSubjectRulesReview", "version": "" }, "scope": "Cluster", "singularResource": "selfsubjectrulesreview", "verbs": [ "create" ] }, { "resource": "subjectaccessreviews", "responseKind": { "group": "", "kind": "SubjectAccessReview", "version": "" }, "scope": "Cluster", "singularResource": "subjectaccessreview", "verbs": [ "create" ] } ], "version": "v1" } ] }, { "metadata": { "creationTimestamp": null, "name": "autoscaling" }, "versions": [ { "freshness": "Current", "resources": [ { "categories": [ "all" ], "resource": "horizontalpodautoscalers", "responseKind": { "group": "", "kind": "HorizontalPodAutoscaler", "version": "" }, "scope": "Namespaced", "shortNames": [ "hpa" ], "singularResource": "horizontalpodautoscaler", "subresources": [ { "responseKind": { "group": "", "kind": "HorizontalPodAutoscaler", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v2" }, { "freshness": "Current", "resources": [ { "categories": [ "all" ], "resource": "horizontalpodautoscalers", "responseKind": { "group": "", "kind": "HorizontalPodAutoscaler", "version": "" }, "scope": "Namespaced", "shortNames": [ "hpa" ], "singularResource": "horizontalpodautoscaler", "subresources": [ { "responseKind": { "group": "", "kind": "HorizontalPodAutoscaler", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1" } ] }, { "metadata": { "creationTimestamp": null, "name": "batch" }, "versions": [ { "freshness": "Current", "resources": [ { "categories": [ "all" ], "resource": "cronjobs", "responseKind": { "group": "", "kind": "CronJob", "version": "" }, "scope": "Namespaced", "shortNames": [ "cj" ], "singularResource": "cronjob", "subresources": [ { "responseKind": { "group": "", "kind": "CronJob", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "categories": [ "all" ], "resource": "jobs", "responseKind": { "group": "", "kind": "Job", "version": "" }, "scope": "Namespaced", "singularResource": "job", "subresources": [ { "responseKind": { "group": "", "kind": "Job", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1" } ] }, { "metadata": { "creationTimestamp": null, "name": "certificates.k8s.io" }, "versions": [ { "freshness": "Current", "resources": [ { "resource": "certificatesigningrequests", "responseKind": { "group": "", "kind": "CertificateSigningRequest", "version": "" }, "scope": "Cluster", "shortNames": [ "csr" ], "singularResource": "certificatesigningrequest", "subresources": [ { "responseKind": { "group": "", "kind": "CertificateSigningRequest", "version": "" }, "subresource": "approval", "verbs": [ "get", "patch", "update" ] }, { "responseKind": { "group": "", "kind": "CertificateSigningRequest", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1" }, { "freshness": "Current", "resources": [ { "resource": "clustertrustbundles", "responseKind": { "group": "", "kind": "ClusterTrustBundle", "version": "" }, "scope": "Cluster", "singularResource": "clustertrustbundle", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1alpha1" } ] }, { "metadata": { "creationTimestamp": null, "name": "networking.k8s.io" }, "versions": [ { "freshness": "Current", "resources": [ { "resource": "ingressclasses", "responseKind": { "group": "", "kind": "IngressClass", "version": "" }, "scope": "Cluster", "singularResource": "ingressclass", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "resource": "ingresses", "responseKind": { "group": "", "kind": "Ingress", "version": "" }, "scope": "Namespaced", "shortNames": [ "ing" ], "singularResource": "ingress", "subresources": [ { "responseKind": { "group": "", "kind": "Ingress", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "resource": "networkpolicies", "responseKind": { "group": "", "kind": "NetworkPolicy", "version": "" }, "scope": "Namespaced", "shortNames": [ "netpol" ], "singularResource": "networkpolicy", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1" }, { "freshness": "Current", "resources": [ { "resource": "ipaddresses", "responseKind": { "group": "", "kind": "IPAddress", "version": "" }, "scope": "Cluster", "shortNames": [ "ip" ], "singularResource": "ipaddress", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "resource": "servicecidrs", "responseKind": { "group": "", "kind": "ServiceCIDR", "version": "" }, "scope": "Cluster", "singularResource": "servicecidr", "subresources": [ { "responseKind": { "group": "", "kind": "ServiceCIDR", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1beta1" } ] }, { "metadata": { "creationTimestamp": null, "name": "policy" }, "versions": [ { "freshness": "Current", "resources": [ { "resource": "poddisruptionbudgets", "responseKind": { "group": "", "kind": "PodDisruptionBudget", "version": "" }, "scope": "Namespaced", "shortNames": [ "pdb" ], "singularResource": "poddisruptionbudget", "subresources": [ { "responseKind": { "group": "", "kind": "PodDisruptionBudget", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1" } ] }, { "metadata": { "creationTimestamp": null, "name": "rbac.authorization.k8s.io" }, "versions": [ { "freshness": "Current", "resources": [ { "resource": "clusterrolebindings", "responseKind": { "group": "", "kind": "ClusterRoleBinding", "version": "" }, "scope": "Cluster", "singularResource": "clusterrolebinding", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "resource": "clusterroles", "responseKind": { "group": "", "kind": "ClusterRole", "version": "" }, "scope": "Cluster", "singularResource": "clusterrole", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "resource": "rolebindings", "responseKind": { "group": "", "kind": "RoleBinding", "version": "" }, "scope": "Namespaced", "singularResource": "rolebinding", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "resource": "roles", "responseKind": { "group": "", "kind": "Role", "version": "" }, "scope": "Namespaced", "singularResource": "role", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1" } ] }, { "metadata": { "creationTimestamp": null, "name": "storage.k8s.io" }, "versions": [ { "freshness": "Current", "resources": [ { "resource": "csidrivers", "responseKind": { "group": "", "kind": "CSIDriver", "version": "" }, "scope": "Cluster", "singularResource": "csidriver", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "resource": "csinodes", "responseKind": { "group": "", "kind": "CSINode", "version": "" }, "scope": "Cluster", "singularResource": "csinode", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "resource": "csistoragecapacities", "responseKind": { "group": "", "kind": "CSIStorageCapacity", "version": "" }, "scope": "Namespaced", "singularResource": "csistoragecapacity", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "resource": "storageclasses", "responseKind": { "group": "", "kind": "StorageClass", "version": "" }, "scope": "Cluster", "shortNames": [ "sc" ], "singularResource": "storageclass", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "resource": "volumeattachments", "responseKind": { "group": "", "kind": "VolumeAttachment", "version": "" }, "scope": "Cluster", "singularResource": "volumeattachment", "subresources": [ { "responseKind": { "group": "", "kind": "VolumeAttachment", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1" }, { "freshness": "Current", "resources": [ { "resource": "volumeattributesclasses", "responseKind": { "group": "", "kind": "VolumeAttributesClass", "version": "" }, "scope": "Cluster", "shortNames": [ "vac" ], "singularResource": "volumeattributesclass", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1beta1" }, { "freshness": "Current", "resources": [ { "resource": "volumeattributesclasses", "responseKind": { "group": "", "kind": "VolumeAttributesClass", "version": "" }, "scope": "Cluster", "shortNames": [ "vac" ], "singularResource": "volumeattributesclass", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1alpha1" } ] }, { "metadata": { "creationTimestamp": null, "name": "admissionregistration.k8s.io" }, "versions": [ { "freshness": "Current", "resources": [ { "categories": [ "api-extensions" ], "resource": "mutatingwebhookconfigurations", "responseKind": { "group": "", "kind": "MutatingWebhookConfiguration", "version": "" }, "scope": "Cluster", "singularResource": "mutatingwebhookconfiguration", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "categories": [ "api-extensions" ], "resource": "validatingadmissionpolicies", "responseKind": { "group": "", "kind": "ValidatingAdmissionPolicy", "version": "" }, "scope": "Cluster", "singularResource": "validatingadmissionpolicy", "subresources": [ { "responseKind": { "group": "", "kind": "ValidatingAdmissionPolicy", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "categories": [ "api-extensions" ], "resource": "validatingadmissionpolicybindings", "responseKind": { "group": "", "kind": "ValidatingAdmissionPolicyBinding", "version": "" }, "scope": "Cluster", "singularResource": "validatingadmissionpolicybinding", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "categories": [ "api-extensions" ], "resource": "validatingwebhookconfigurations", "responseKind": { "group": "", "kind": "ValidatingWebhookConfiguration", "version": "" }, "scope": "Cluster", "singularResource": "validatingwebhookconfiguration", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1" }, { "freshness": "Current", "resources": [ { "categories": [ "api-extensions" ], "resource": "validatingadmissionpolicies", "responseKind": { "group": "", "kind": "ValidatingAdmissionPolicy", "version": "" }, "scope": "Cluster", "singularResource": "validatingadmissionpolicy", "subresources": [ { "responseKind": { "group": "", "kind": "ValidatingAdmissionPolicy", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "categories": [ "api-extensions" ], "resource": "validatingadmissionpolicybindings", "responseKind": { "group": "", "kind": "ValidatingAdmissionPolicyBinding", "version": "" }, "scope": "Cluster", "singularResource": "validatingadmissionpolicybinding", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1beta1" }, { "freshness": "Current", "resources": [ { "categories": [ "api-extensions" ], "resource": "validatingadmissionpolicies", "responseKind": { "group": "", "kind": "ValidatingAdmissionPolicy", "version": "" }, "scope": "Cluster", "singularResource": "validatingadmissionpolicy", "subresources": [ { "responseKind": { "group": "", "kind": "ValidatingAdmissionPolicy", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "categories": [ "api-extensions" ], "resource": "validatingadmissionpolicybindings", "responseKind": { "group": "", "kind": "ValidatingAdmissionPolicyBinding", "version": "" }, "scope": "Cluster", "singularResource": "validatingadmissionpolicybinding", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1alpha1" } ] }, { "metadata": { "creationTimestamp": null, "name": "apiextensions.k8s.io" }, "versions": [ { "freshness": "Current", "resources": [ { "categories": [ "api-extensions" ], "resource": "customresourcedefinitions", "responseKind": { "group": "", "kind": "CustomResourceDefinition", "version": "" }, "scope": "Cluster", "shortNames": [ "crd", "crds" ], "singularResource": "customresourcedefinition", "subresources": [ { "responseKind": { "group": "", "kind": "CustomResourceDefinition", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1" } ] }, { "metadata": { "creationTimestamp": null, "name": "scheduling.k8s.io" }, "versions": [ { "freshness": "Current", "resources": [ { "resource": "priorityclasses", "responseKind": { "group": "", "kind": "PriorityClass", "version": "" }, "scope": "Cluster", "shortNames": [ "pc" ], "singularResource": "priorityclass", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1" } ] }, { "metadata": { "creationTimestamp": null, "name": "coordination.k8s.io" }, "versions": [ { "freshness": "Current", "resources": [ { "resource": "leases", "responseKind": { "group": "", "kind": "Lease", "version": "" }, "scope": "Namespaced", "singularResource": "lease", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1" }, { "freshness": "Current", "resources": [ { "resource": "leasecandidates", "responseKind": { "group": "", "kind": "LeaseCandidate", "version": "" }, "scope": "Namespaced", "singularResource": "leasecandidate", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1alpha1" } ] }, { "metadata": { "creationTimestamp": null, "name": "node.k8s.io" }, "versions": [ { "freshness": "Current", "resources": [ { "resource": "runtimeclasses", "responseKind": { "group": "", "kind": "RuntimeClass", "version": "" }, "scope": "Cluster", "singularResource": "runtimeclass", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1" } ] }, { "metadata": { "creationTimestamp": null, "name": "discovery.k8s.io" }, "versions": [ { "freshness": "Current", "resources": [ { "resource": "endpointslices", "responseKind": { "group": "", "kind": "EndpointSlice", "version": "" }, "scope": "Namespaced", "singularResource": "endpointslice", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1" } ] }, { "metadata": { "creationTimestamp": null, "name": "flowcontrol.apiserver.k8s.io" }, "versions": [ { "freshness": "Current", "resources": [ { "resource": "flowschemas", "responseKind": { "group": "", "kind": "FlowSchema", "version": "" }, "scope": "Cluster", "singularResource": "flowschema", "subresources": [ { "responseKind": { "group": "", "kind": "FlowSchema", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "resource": "prioritylevelconfigurations", "responseKind": { "group": "", "kind": "PriorityLevelConfiguration", "version": "" }, "scope": "Cluster", "singularResource": "prioritylevelconfiguration", "subresources": [ { "responseKind": { "group": "", "kind": "PriorityLevelConfiguration", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1" }, { "freshness": "Current", "resources": [ { "resource": "flowschemas", "responseKind": { "group": "", "kind": "FlowSchema", "version": "" }, "scope": "Cluster", "singularResource": "flowschema", "subresources": [ { "responseKind": { "group": "", "kind": "FlowSchema", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "resource": "prioritylevelconfigurations", "responseKind": { "group": "", "kind": "PriorityLevelConfiguration", "version": "" }, "scope": "Cluster", "singularResource": "prioritylevelconfiguration", "subresources": [ { "responseKind": { "group": "", "kind": "PriorityLevelConfiguration", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1beta3" } ] }, { "metadata": { "creationTimestamp": null, "name": "internal.apiserver.k8s.io" }, "versions": [ { "freshness": "Current", "resources": [ { "resource": "storageversions", "responseKind": { "group": "", "kind": "StorageVersion", "version": "" }, "scope": "Cluster", "singularResource": "storageversion", "subresources": [ { "responseKind": { "group": "", "kind": "StorageVersion", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1alpha1" } ] }, { "metadata": { "creationTimestamp": null, "name": "resource.k8s.io" }, "versions": [ { "freshness": "Current", "resources": [ { "resource": "deviceclasses", "responseKind": { "group": "", "kind": "DeviceClass", "version": "" }, "scope": "Cluster", "singularResource": "deviceclass", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "resource": "podschedulingcontexts", "responseKind": { "group": "", "kind": "PodSchedulingContext", "version": "" }, "scope": "Namespaced", "singularResource": "podschedulingcontext", "subresources": [ { "responseKind": { "group": "", "kind": "PodSchedulingContext", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "resource": "resourceclaims", "responseKind": { "group": "", "kind": "ResourceClaim", "version": "" }, "scope": "Namespaced", "singularResource": "resourceclaim", "subresources": [ { "responseKind": { "group": "", "kind": "ResourceClaim", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "resource": "resourceclaimtemplates", "responseKind": { "group": "", "kind": "ResourceClaimTemplate", "version": "" }, "scope": "Namespaced", "singularResource": "resourceclaimtemplate", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] }, { "resource": "resourceslices", "responseKind": { "group": "", "kind": "ResourceSlice", "version": "" }, "scope": "Cluster", "singularResource": "resourceslice", "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1alpha3" } ] }, { "metadata": { "creationTimestamp": null, "name": "storagemigration.k8s.io" }, "versions": [ { "freshness": "Current", "resources": [ { "resource": "storageversionmigrations", "responseKind": { "group": "", "kind": "StorageVersionMigration", "version": "" }, "scope": "Cluster", "singularResource": "storageversionmigration", "subresources": [ { "responseKind": { "group": "", "kind": "StorageVersionMigration", "version": "" }, "subresource": "status", "verbs": [ "get", "patch", "update" ] } ], "verbs": [ "create", "delete", "deletecollection", "get", "list", "patch", "update", "watch" ] } ], "version": "v1alpha1" } ] } ], "kind": "APIGroupDiscoveryList", "metadata": {} } </del>


if !pluginStatus.IsUnschedulable() { // Filter plugins are not supposed to return any status other than // Success or Unschedulable. <del> errStatus := framework.AsStatus(fmt.Errorf("running %q filter plugin: %w", pl.Name(), pluginStatus.AsError())).WithFailedPlugin(pl.Name()) return map[string]*framework.Status{pl.Name(): errStatus} </del> <ins> pluginStatus = framework.AsStatus(fmt.Errorf("running %q filter plugin: %w", pl.Name(), pluginStatus.AsError())) </ins> } pluginStatus.SetFailedPlugin(pl.Name()) <del> statuses[pl.Name()] = pluginStatus </del> <ins> return map[string]*framework.Status{pl.Name(): pluginStatus} </ins> } }


} } <ins> func TestDescribePodSecurityPolicy(t *testing.T) { expected := []string{ "Name:t*mypsp", "Allow Privileged:t*false", "Default Add Capabilities:t*<none>", "Required Drop Capabilities:t*<none>", "Allowed Capabilities:t*<none>", "Allowed Volume Types:t*<none>", "Allow Host Network:t*false", "Allow Host Ports:t*<none>", "Allow Host PID:t*false", "Allow Host IPC:t*false", "Read Only Root Filesystem:t*false", "SELinux Context Strategy: RunAsAny", "User:t*<none>", "Role:t*<none>", "Type:t*<none>", "Level:t*<none>", "Run As User Strategy: RunAsAny", "FSGroup Strategy: RunAsAny", "Supplemental Groups Strategy: RunAsAny", } fake := fake.NewSimpleClientset(&extensions.PodSecurityPolicy{ ObjectMeta: metav1.ObjectMeta{ Name: "mypsp", }, Spec: extensions.PodSecurityPolicySpec{ SELinux: extensions.SELinuxStrategyOptions{ Rule: extensions.SELinuxStrategyRunAsAny, }, RunAsUser: extensions.RunAsUserStrategyOptions{ Rule: extensions.RunAsUserStrategyRunAsAny, }, FSGroup: extensions.FSGroupStrategyOptions{ Rule: extensions.FSGroupStrategyRunAsAny, }, SupplementalGroups: extensions.SupplementalGroupsStrategyOptions{ Rule: extensions.SupplementalGroupsStrategyRunAsAny, }, }, }) c := &describeClient{T: t, Namespace: "", Interface: fake} d := PodSecurityPolicyDescriber{c} out, err := d.Describe("", "mypsp", printers.DescriberSettings{}) if err != nil { t.Fatalf("unexpected error: %v", err) } for _, item := range expected { if matched, _ := regexp.MatchString(item, out); !matched { t.Errorf("Expected to find %q in: %q", item, out) } } } </ins> func TestDescribeResourceQuota(t *testing.T) { fake := fake.NewSimpleClientset(&api.ResourceQuota{ ObjectMeta: metav1.ObjectMeta{


createdConts.Insert(p[:n-8]) } } <del> // We expect 9: 2 pod infra containers + 2 pods from the replication controller + //              1 pod infra container + 2 pods from the URL + //              1 pod infra container + 1 pod from the service test. // In addition, runStaticPodTest creates 1 pod infra containers + //                                       1 pod container from the mainfest file // The total number of container created is 11 </del> <ins> // We expect 9: 2 pod infra containers + 2 containers from the replication controller + //              1 pod infra container + 2 containers from the URL on first Kubelet + //              1 pod infra container + 2 containers from the URL on second Kubelet + //              1 pod infra container + 1 container from the service test. // In addition, runStaticPodTest creates 2 pod infra containers + //                                       2 pod containers from the file (1 for manifest and 1 for spec) // The total number of container created is 13 </ins> <del> if len(createdConts) != 11 { glog.Fatalf("Expected 11 containers; got %vnnlist of created containers:nn%#vnnDocker 1 Created:nn%#vnnDocker 2 Created:nn%#vnn", len(createdConts), createdConts.List(), fakeDocker1.Created, fakeDocker2.Created) </del> <ins> if len(createdConts) != 16 { glog.Fatalf("Expected 16 containers; got %vnnlist of created containers:nn%#vnnDocker 1 Created:nn%#vnnDocker 2 Created:nn%#vnn", len(createdConts), createdConts.List(), fakeDocker1.Created, fakeDocker2.Created) </ins> } glog.Infof("OK - found created containers: %#v", createdConts.List()) } // ServeCachedManifestFile serves a file for kubelet to read. <del> func ServeCachedManifestFile() (servingAddress string) { </del> <ins> func ServeCachedManifestFile(contents string) (servingAddress string) { </ins> server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/manifest" { <del> w.Write([]byte(testManifestFile)) </del> <ins> w.Write([]byte(contents)) </ins> return } glog.Fatalf("Got request: %#vn", r)


command: - /heapster - --source=kubernetes.summary_api:'' <del> - image: gcr.io/google_containers/addon-resizer:1.5 </del> <ins> - image: gcr.io/google_containers/addon-resizer:1.6 </ins> name: heapster-nanny resources: limits:


testAPIVersion = "testgroup/testversion" ) <del> var scheme *runtime.Scheme func init() { scheme = runtime.NewScheme() metav1.AddMetaToScheme(scheme) } </del> func newPartialObjectMetadata(apiVersion, kind, namespace, name string) *metav1.PartialObjectMetadata { return &metav1.PartialObjectMetadata{ TypeMeta: metav1.TypeMeta{


<del> apiVersion: v1 kind: Service metadata: name: elasticsearch labels: component: elasticsearch role: client spec: type: LoadBalancer selector: component: elasticsearch role: client ports: - name: http port: 9200 protocol: TCP </del>


// More details here: https://github.com/kubernetes/kubernetes/issues/50986 AutoDetectCloudProvider = "auto-detect" <del> defaultIPTablesMasqueradeBit = 14 defaultIPTablesDropBit       = 15 </del> <ins> DefaultIPTablesMasqueradeBit = 14 DefaultIPTablesDropBit       = 15 </ins> ) var ( zeroDuration = metav1.Duration{} // Refer to [Node Allocatable](https://git.k8s.io/community/contributors/design-proposals/node/node-allocatable.md) doc for more information. <del> defaultNodeAllocatableEnforcement = []string{"pods"} </del> <ins> DefaultNodeAllocatableEnforcement = []string{"pods"} </ins> ) func addDefaultingFuncs(scheme *kruntime.Scheme) error {


ExpectedEtcdPath: "/registry/configmaps/" + namespace + "/cm1", }, gvr("", "v1", "services"): { <del> Stub:             `{"metadata": {"name": "service1"}, "spec": {"externalName": "service1name", "ports": [{"port": 10000, "targetPort": 11000}], "selector": {"test": "data"}}}`, </del> <ins> Stub:             `{"metadata": {"name": "service1"}, "spec": {"type": "LoadBalancer", "ports": [{"port": 10000, "targetPort": 11000}], "selector": {"test": "data"}}}`, </ins> ExpectedEtcdPath: "/registry/services/specs/" + namespace + "/service1", }, gvr("", "v1", "podtemplates"): {


defer close(stopCh) manager, informers := testNewReplicaSetControllerFromClient(client, stopCh, BurstReplicas) <del> // A controller with 2 replicas and no pods in the store, 2 creates expected </del> <ins> // A controller with 2 replicas and no active pods in the store. // Inactive pods should be ignored. 2 creates expected. </ins> labelMap := map[string]string{"foo": "bar"} rs := newReplicaSet(2, labelMap) informers.Extensions().V1beta1().ReplicaSets().Informer().GetIndexer().Add(rs) <ins> failedPod := newPod("failed-pod", rs, v1.PodFailed, nil, true) deletedPod := newPod("deleted-pod", rs, v1.PodRunning, nil, true) deletedPod.DeletionTimestamp = &metav1.Time{Time: time.Now()} informers.Core().V1().Pods().Informer().GetIndexer().Add(failedPod) informers.Core().V1().Pods().Informer().GetIndexer().Add(deletedPod) </ins> fakePodControl := controller.FakePodControl{} manager.podControl = &fakePodControl


// Represents the requirement on the container exit codes. // +optional <del> OnExitCodes *PodFailurePolicyOnExitCodesRequirement `json:"onExitCodes" protobuf:"bytes,2,opt,name=onExitCodes"` </del> <ins> OnExitCodes *PodFailurePolicyOnExitCodesRequirement `json:"onExitCodes,omitempty" protobuf:"bytes,2,opt,name=onExitCodes"` </ins> // Represents the requirement on the pod conditions. The requirement is represented // as a list of pod condition patterns. The requirement is satisfied if at // least one pattern matches an actual pod condition. At most 20 elements are allowed. // +listType=atomic // +optional <del> OnPodConditions []PodFailurePolicyOnPodConditionsPattern `json:"onPodConditions" protobuf:"bytes,3,opt,name=onPodConditions"` </del> <ins> OnPodConditions []PodFailurePolicyOnPodConditionsPattern `json:"onPodConditions,omitempty" protobuf:"bytes,3,opt,name=onPodConditions"` </ins> } // PodFailurePolicy describes how failed pods influence the backoffLimit.


}) ginkgo.It("Kubelet's oom-score-adj should be -999", func() { kubeletPids, err := getPidsForProcess(kubeletProcessName, "") <del> gomega.Expect(err).To(gomega.BeNil(), "failed to get list of kubelet pids") </del> <ins> framework.ExpectNoError(err, "failed to get list of kubelet pids") </ins> framework.ExpectEqual(len(kubeletPids), 1, "expected only one kubelet process; found %d", len(kubeletPids)) gomega.Eventually(func() error { return validateOOMScoreAdjSetting(kubeletPids[0], -999)


} sgList := []string{securityGroupID} <del> for _, extraSG := range strings.Split(annotation, ",") { </del> <ins> for _, extraSG := range strings.Split(annotations[ServiceAnnotationLoadBalancerExtraSecurityGroups], ",") { </ins> extraSG = strings.TrimSpace(extraSG) if len(extraSG) > 0 { sgList = append(sgList, extraSG)


expectMetrics(t, expectedMetrics{desiredSlices: 1, actualSlices: 1, desiredEndpoints: 10, addedPerSync: 20, removedPerSync: 10, numCreated: 1, numUpdated: 1, numDeleted: 0}) } <ins> // When a Service has a non-nil deletionTimestamp we want to avoid creating any // new EndpointSlices but continue to allow updates and deletes through. This // test uses 3 EndpointSlices, 1 "to-create", 1 "to-update", and 1 "to-delete". // Each test case exercises different combinations of calls to finalize with // those resources. func TestReconcilerFinalizeSvcDeletionTimestamp(t *testing.T) { now := metav1.Now() testCases := []struct { name               string deletionTimestamp  *metav1.Time attemptCreate      bool attemptUpdate      bool attemptDelete      bool expectCreatedSlice bool expectUpdatedSlice bool expectDeletedSlice bool }{{ name:               "Attempt create and update, nil deletion timestamp", deletionTimestamp:  nil, attemptCreate:      true, attemptUpdate:      true, expectCreatedSlice: true, expectUpdatedSlice: true, expectDeletedSlice: true, }, { name:               "Attempt create and update, deletion timestamp set", deletionTimestamp:  &now, attemptCreate:      true, attemptUpdate:      true, expectCreatedSlice: false, expectUpdatedSlice: true, expectDeletedSlice: true, }, { // Slice scheduled for creation is transitioned to update of Slice // scheduled for deletion. name:               "Attempt create, update, and delete, nil deletion timestamp, recycling in action", deletionTimestamp:  nil, attemptCreate:      true, attemptUpdate:      true, attemptDelete:      true, expectCreatedSlice: false, expectUpdatedSlice: true, expectDeletedSlice: true, }, { // Slice scheduled for creation is transitioned to update of Slice // scheduled for deletion. name:               "Attempt create, update, and delete, deletion timestamp set, recycling in action", deletionTimestamp:  &now, attemptCreate:      true, attemptUpdate:      true, attemptDelete:      true, expectCreatedSlice: false, expectUpdatedSlice: true, expectDeletedSlice: true, }, { // Update and delete continue to work when deletionTimestamp is set. name:               "Attempt update delete, deletion timestamp set", deletionTimestamp:  &now, attemptCreate:      false, attemptUpdate:      true, attemptDelete:      true, expectCreatedSlice: false, expectUpdatedSlice: true, expectDeletedSlice: false, }} for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { client := newClientset() setupMetrics() r := newReconciler(client, []*corev1.Node{{ObjectMeta: metav1.ObjectMeta{Name: "node-1"}}}, defaultMaxEndpointsPerSlice) namespace := "test" svc, endpointMeta := newServiceAndEndpointMeta("foo", namespace) svc.DeletionTimestamp = tc.deletionTimestamp esToCreate := &discovery.EndpointSlice{ ObjectMeta:  metav1.ObjectMeta{Name: "to-create"}, AddressType: endpointMeta.AddressType, Ports:       endpointMeta.Ports, } // Add EndpointSlice that can be updated. esToUpdate, err := client.DiscoveryV1beta1().EndpointSlices(namespace).Create(context.TODO(), &discovery.EndpointSlice{ ObjectMeta:  metav1.ObjectMeta{Name: "to-update"}, AddressType: endpointMeta.AddressType, Ports:       endpointMeta.Ports, }, metav1.CreateOptions{}) if err != nil { t.Fatalf("Expected no error creating EndpointSlice during test setup, got %v", err) } // Add an endpoint so we can see if this has actually been updated by // finalize func. esToUpdate.Endpoints = []discovery.Endpoint{{Addresses: []string{"10.2.3.4"}}} // Add EndpointSlice that can be deleted. esToDelete, err := client.DiscoveryV1beta1().EndpointSlices(namespace).Create(context.TODO(), &discovery.EndpointSlice{ ObjectMeta:  metav1.ObjectMeta{Name: "to-delete"}, AddressType: endpointMeta.AddressType, Ports:       endpointMeta.Ports, }, metav1.CreateOptions{}) if err != nil { t.Fatalf("Expected no error creating EndpointSlice during test setup, got %v", err) } slicesToCreate := []*discovery.EndpointSlice{} if tc.attemptCreate { slicesToCreate = append(slicesToCreate, esToCreate.DeepCopy()) } slicesToUpdate := []*discovery.EndpointSlice{} if tc.attemptUpdate { slicesToUpdate = append(slicesToUpdate, esToUpdate.DeepCopy()) } slicesToDelete := []*discovery.EndpointSlice{} if tc.attemptDelete { slicesToDelete = append(slicesToDelete, esToDelete.DeepCopy()) } err = r.finalize(&svc, slicesToCreate, slicesToUpdate, slicesToDelete, time.Now()) if err != nil { t.Errorf("Error calling r.finalize(): %v", err) } fetchedSlices := fetchEndpointSlices(t, client, namespace) createdSliceFound := false updatedSliceFound := false deletedSliceFound := false for _, epSlice := range fetchedSlices { if epSlice.Name == esToCreate.Name { createdSliceFound = true } if epSlice.Name == esToUpdate.Name { updatedSliceFound = true if tc.attemptUpdate && len(epSlice.Endpoints) != len(esToUpdate.Endpoints) { t.Errorf("Expected EndpointSlice to be updated with %d endpoints, got %d endpoints", len(esToUpdate.Endpoints), len(epSlice.Endpoints)) } } if epSlice.Name == esToDelete.Name { deletedSliceFound = true } } if createdSliceFound != tc.expectCreatedSlice { t.Errorf("Expected created EndpointSlice existence to be %t, got %t", tc.expectCreatedSlice, createdSliceFound) } if updatedSliceFound != tc.expectUpdatedSlice { t.Errorf("Expected updated EndpointSlice existence to be %t, got %t", tc.expectUpdatedSlice, updatedSliceFound) } if deletedSliceFound != tc.expectDeletedSlice { t.Errorf("Expected deleted EndpointSlice existence to be %t, got %t", tc.expectDeletedSlice, deletedSliceFound) } }) } } </ins> // Test Helpers func newReconciler(client *fake.Clientset, nodes []*corev1.Node, maxEndpointsPerSlice int32) *reconciler {


<del> apiVersion: v1 kind: ReplicationController metadata: name: es labels: component: elasticsearch spec: replicas: 1 template: metadata: labels: component: elasticsearch spec: serviceAccount: elasticsearch containers: - name: es securityContext: capabilities: add: - IPC_LOCK image: quay.io/pires/docker-elasticsearch-kubernetes:1.7.1-4 env: - name: KUBERNETES_CA_CERTIFICATE_FILE value: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt - name: NAMESPACE valueFrom: fieldRef: fieldPath: metadata.namespace - name: "CLUSTER_NAME" value: "myesdb" - name: "DISCOVERY_SERVICE" value: "elasticsearch" - name: NODE_MASTER value: "true" - name: NODE_DATA value: "true" - name: HTTP_ENABLE value: "true" ports: - containerPort: 9200 name: http protocol: TCP - containerPort: 9300 name: transport protocol: TCP volumeMounts: - mountPath: /data name: storage volumes: - name: storage emptyDir: {} </del>


import ( "context" <ins> "encoding/json" </ins> "fmt" "math/rand" "time"


WithStdinData("abcd1234n"). ExecOrDie() gomega.Expect(runOutput).ToNot(gomega.ContainSubstring("stdin closed")) <del> g = func(pods []*v1.Pod) sort.Interface { return sort.Reverse(controller.ActivePods(pods)) } runTestPod, _, err = polymorphichelpers.GetFirstPod(f.ClientSet.CoreV1(), ns, "run=run-test-3", 1*time.Minute, g) </del> <ins> g := func(pods []*v1.Pod) sort.Interface { return sort.Reverse(controller.ActivePods(pods)) } runTestPod, _, err := polymorphichelpers.GetFirstPod(f.ClientSet.CoreV1(), ns, "run=run-test-3", 1*time.Minute, g) </ins> gomega.Expect(err).To(gomega.BeNil()) if !e2epod.CheckPodsRunningReady(c, ns, []string{runTestPod.Name}, time.Minute) { e2elog.Failf("Pod %q of Job %q should still be running", runTestPod.Name, "run-test-3")


valueFrom: fieldRef: fieldPath: metadata.name <del> command: - /bin/sh - -c - /kubemark --morph=kubelet --name=$(NODE_NAME) {{hollow_kubelet_params}} --kubeconfig=/kubeconfig/kubelet.kubeconfig $(CONTENT_TYPE) --alsologtostderr 1>>/var/log/kubelet-$(NODE_NAME).log 2>&1 </del> <ins> command: [ "/kubemark", "--morph=kubelet", "--name=$(NODE_NAME)", "--kubeconfig=/kubeconfig/kubelet.kubeconfig", "$(CONTENT_TYPE)", "--log-file=/var/log/kubelet-$(NODE_NAME).log", "--logtostderr=false", {{hollow_kubelet_params}} ] </ins> volumeMounts: - name: kubeconfig-volume mountPath: /kubeconfig


"//vendor/github.com/onsi/gomega:go_default_library", "//vendor/k8s.io/api/core/v1:go_default_library", "//vendor/k8s.io/api/settings/v1alpha1:go_default_library", <ins> "//vendor/k8s.io/apimachinery/pkg/api/errors:go_default_library", </ins> "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", "//vendor/k8s.io/apimachinery/pkg/labels:go_default_library", "//vendor/k8s.io/apimachinery/pkg/watch:go_default_library",


} // apply volume ownership <del> if !c.readOnly && fsGroup != nil { err := volume.SetVolumeOwnership(c, fsGroup) if err != nil { // attempt to rollback mount. glog.Error(log("mounter.SetupAt failed to set fsgroup volume ownership for [%s]: %v", c.volumeID, err)) glog.V(4).Info(log("mounter.SetupAt attempting to unpublish volume %s due to previous error", c.volumeID)) if unpubErr := csi.NodeUnpublishVolume(ctx, c.volumeID, dir); unpubErr != nil { glog.Error(log( "mounter.SetupAt failed to unpublish volume [%s]: %v (caused by previous NodePublish error: %v)", c.volumeID, unpubErr, err, )) return fmt.Errorf("%v (caused by %v)", unpubErr, err) } </del> <ins> // The following logic is derived from https://github.com/kubernetes/kubernetes/issues/66323 // if fstype is "", then skip fsgroup (could be indication of non-block filesystem) // if fstype is provided and pv.AccessMode == ReadWriteOnly, then apply fsgroup </ins> <del> if unmountErr := removeMountDir(c.plugin, dir); unmountErr != nil { glog.Error(log( "mounter.SetupAt failed to clean mount dir [%s]: %v (caused by previous NodePublish error: %v)", dir, unmountErr, err, )) return fmt.Errorf("%v (caused by %v)", unmountErr, err) } </del> <ins> err = c.applyFSGroup(fsType, fsGroup) if err != nil { // attempt to rollback mount. fsGrpErr := fmt.Errorf("applyFSGroup failed for vol %s: %v", c.volumeID, err) if unpubErr := csi.NodeUnpublishVolume(ctx, c.volumeID, dir); unpubErr != nil { glog.Error(log("NodeUnpublishVolume failed for [%s]: %v", c.volumeID, unpubErr)) return fsGrpErr } </ins> <del> return err </del> <ins> if unmountErr := removeMountDir(c.plugin, dir); unmountErr != nil { glog.Error(log("removeMountDir failed for [%s]: %v", dir, unmountErr)) return fsGrpErr </ins> } <del> glog.V(4).Info(log("mounter.SetupAt sets fsGroup to [%d] for %s", *fsGroup, c.volumeID)) </del> <ins> return fsGrpErr </ins> } glog.V(4).Infof(log("mounter.SetUp successfully requested NodePublish [%s]", dir))


"//cmd/kube-proxy/app:go_default_library", "//pkg/client/metrics/prometheus:go_default_library", "//pkg/version/prometheus:go_default_library", <ins> "//vendor/github.com/spf13/pflag:go_default_library", </ins> "//vendor/k8s.io/apiserver/pkg/util/flag:go_default_library", "//vendor/k8s.io/apiserver/pkg/util/logs:go_default_library", ],


} ip, err := az.getIPForMachine(name) if err != nil { <del> glog.Errorf("error: az.NodeAddresses, az.getIPForMachine(%s), err=%v", name, err) return nil, err </del> <ins> if az.CloudProviderBackoff { glog.V(2).Infof("NodeAddresses(%s) backing off", name) ip, err = az.GetIPForMachineWithRetry(name) if err != nil { glog.V(2).Infof("NodeAddresses(%s) abort backoff", name) return nil, err } } else { glog.Errorf("error: az.NodeAddresses, az.getIPForMachine(%s), err=%v", name, err) return nil, err } </ins> } return []v1.NodeAddress{


'${MASTER_IP}' create-flanneld-opts '127.0.0.1' '${MASTER_IP}' <del> sudo -E -p '[sudo] password to start master: ' -- /bin/bash -ce ' </del> <ins> FLANNEL_OTHER_NET_CONFIG='${FLANNEL_OTHER_NET_CONFIG}' sudo -E -p '[sudo] password to start master: ' -- /bin/bash -ce ' </ins> ${BASH_DEBUG_FLAGS} cp ~/kube/default/* /etc/default/ cp ~/kube/init_conf/* /etc/init/


}{ { code:     http.StatusBadRequest, <del> expected: true, </del> <ins> expected: false, </ins> }, { code:     http.StatusInternalServerError,


func subnet(service *v1.Service) *string { if requiresInternalLoadBalancer(service) { <del> if l, found := service.Annotations[ServiceAnnotationLoadBalancerInternalSubnet]; found { </del> <ins> if l, found := service.Annotations[ServiceAnnotationLoadBalancerInternalSubnet]; found && strings.TrimSpace(l) != "" { </ins> return &l } }


}, }, }, <ins> Required: []string{"versions"}, </ins> }, }, Dependencies: []string{


statefulSetTimeout = 10 * time.Minute // statefulPodTimeout is a timeout for stateful pods to change state statefulPodTimeout = 5 * time.Minute <ins> testFinalizer = "example.com/test-finalizer" </ins> ) var httpProbe = &v1.Probe{


expectedErrMsg:      fmt.Errorf("getError"), }, { <del> name:                "InstanceMetadataByProviderID should report error if VMSS instanceID is invalid", metadataName:        "vmss_$123", providerID:          providerID, vmType:              vmTypeVMSS, useInstanceMetadata: true, expectedErrMsg:      fmt.Errorf("failed to parse VMSS instanceID %q: strconv.ParseInt: parsing %q: invalid syntax", "$123", "$123"), }, { </del> name:         "InstanceMetadataByProviderID should get metadata from Azure API if cloud.UseInstanceMetadata is false", metadataName: "vm1", providerID:   providerID,


<ins> /* Copyright 2022 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 plugin import ( "context" "errors" "fmt" "time" v1 "k8s.io/api/core/v1" resourceapi "k8s.io/api/resource/v1alpha3" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/fields" utilversion "k8s.io/apimachinery/pkg/util/version" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" "k8s.io/klog/v2" "k8s.io/kubernetes/pkg/kubelet/pluginmanager/cache" ) // defaultClientCallTimeout is the default amount of time that a DRA driver has // to respond to any of the gRPC calls. kubelet uses this value by passing nil // to RegisterPlugin. Some tests use a different, usually shorter timeout to // speed up testing. // // This is half of the kubelet retry period (according to // https://github.com/kubernetes/kubernetes/commit/0449cef8fd5217d394c5cd331d852bd50983e6b3). const defaultClientCallTimeout = 45 * time.Second // RegistrationHandler is the handler which is fed to the pluginwatcher API. type RegistrationHandler struct { // backgroundCtx is used for all future activities of the handler. // This is necessary because it implements APIs which don't // provide a context. backgroundCtx context.Context kubeClient    kubernetes.Interface getNode       func() (*v1.Node, error) } var _ cache.PluginHandler = &RegistrationHandler{} // NewPluginHandler returns new registration handler. // // Must only be called once per process because it manages global state. // If a kubeClient is provided, then it synchronizes ResourceSlices // with the resource information provided by plugins. func NewRegistrationHandler(kubeClient kubernetes.Interface, getNode func() (*v1.Node, error)) *RegistrationHandler { handler := &RegistrationHandler{ // The context and thus logger should come from the caller. backgroundCtx: klog.NewContext(context.TODO(), klog.LoggerWithName(klog.TODO(), "DRA registration handler")), kubeClient:    kubeClient, getNode:       getNode, } // When kubelet starts up, no DRA driver has registered yet. None of // the drivers are usable until they come back, which might not happen // at all. Therefore it is better to not advertise any local resources // because pods could get stuck on the node waiting for the driver // to start up. // // This has to run in the background. go handler.wipeResourceSlices("") return handler } // wipeResourceSlices deletes ResourceSlices of the node, optionally just for a specific driver. func (h *RegistrationHandler) wipeResourceSlices(driver string) { if h.kubeClient == nil { return } ctx := h.backgroundCtx logger := klog.FromContext(ctx) backoff := wait.Backoff{ Duration: time.Second, Factor:   2, Jitter:   0.2, Cap:      5 * time.Minute, Steps:    100, } // Error logging is done inside the loop. Context cancellation doesn't get logged. _ = wait.ExponentialBackoffWithContext(ctx, backoff, func(ctx context.Context) (bool, error) { node, err := h.getNode() if apierrors.IsNotFound(err) { return false, nil } if err != nil { logger.Error(err, "Unexpected error checking for node") return false, nil } fieldSelector := fields.Set{resourceapi.ResourceSliceSelectorNodeName: node.Name} if driver != "" { fieldSelector[resourceapi.ResourceSliceSelectorDriver] = driver } err = h.kubeClient.ResourceV1alpha3().ResourceSlices().DeleteCollection(ctx, metav1.DeleteOptions{}, metav1.ListOptions{FieldSelector: fieldSelector.String()}) switch { case err == nil: logger.V(3).Info("Deleted ResourceSlices", "fieldSelector", fieldSelector) return true, nil case apierrors.IsUnauthorized(err): // This can happen while kubelet is still figuring out // its credentials. logger.V(5).Info("Deleting ResourceSlice failed, retrying", "fieldSelector", fieldSelector, "err", err) return false, nil default: // Log and retry for other errors. logger.V(3).Info("Deleting ResourceSlice failed, retrying", "fieldSelector", fieldSelector, "err", err) return false, nil } }) } // RegisterPlugin is called when a plugin can be registered. func (h *RegistrationHandler) RegisterPlugin(pluginName string, endpoint string, versions []string, pluginClientTimeout *time.Duration) error { // Prepare a context with its own logger for the plugin. // // The lifecycle of the plugin's background activities is tied to our // root context, so canceling that will also cancel the plugin. // // The logger injects the plugin name as additional value // into all log output related to the plugin. ctx := h.backgroundCtx logger := klog.FromContext(ctx) logger = klog.LoggerWithValues(logger, "pluginName", pluginName) ctx = klog.NewContext(ctx, logger) logger.V(3).Info("Register new DRA plugin", "endpoint", endpoint) highestSupportedVersion, err := h.validateVersions(pluginName, versions) if err != nil { return fmt.Errorf("version check of plugin %s failed: %w", pluginName, err) } var timeout time.Duration if pluginClientTimeout == nil { timeout = defaultClientCallTimeout } else { timeout = *pluginClientTimeout } ctx, cancel := context.WithCancelCause(ctx) pluginInstance := &Plugin{ backgroundCtx:           ctx, cancel:                  cancel, conn:                    nil, endpoint:                endpoint, highestSupportedVersion: highestSupportedVersion, clientCallTimeout:       timeout, } // Storing endpoint of newly registered DRA Plugin into the map, where plugin name will be the key // all other DRA components will be able to get the actual socket of DRA plugins by its name. if draPlugins.add(pluginName, pluginInstance) { logger.V(1).Info("Already registered, previous plugin was replaced") } return nil } func (h *RegistrationHandler) validateVersions( pluginName string, versions []string, ) (*utilversion.Version, error) { if len(versions) == 0 { return nil, errors.New("empty list for supported versions") } // Validate version newPluginHighestVersion, err := utilversion.HighestSupportedVersion(versions) if err != nil { // HighestSupportedVersion includes the list of versions in its error // if relevant, no need to repeat it here. return nil, fmt.Errorf("none of the versions are supported: %w", err) } existingPlugin := draPlugins.get(pluginName) if existingPlugin == nil { return newPluginHighestVersion, nil } if existingPlugin.highestSupportedVersion.LessThan(newPluginHighestVersion) { return newPluginHighestVersion, nil } return nil, fmt.Errorf("another plugin instance is already registered with a higher supported version: %q < %q", newPluginHighestVersion, existingPlugin.highestSupportedVersion) } // DeRegisterPlugin is called when a plugin has removed its socket, // signaling it is no longer available. func (h *RegistrationHandler) DeRegisterPlugin(pluginName string) { if p := draPlugins.delete(pluginName); p != nil { logger := klog.FromContext(p.backgroundCtx) logger.V(3).Info("Deregister DRA plugin", "endpoint", p.endpoint) // Clean up the ResourceSlices for the deleted Plugin since it // may have died without doing so itself and might never come // back. go h.wipeResourceSlices(pluginName) return } logger := klog.FromContext(h.backgroundCtx) logger.V(3).Info("Deregister DRA plugin not necessary, was already removed") } // ValidatePlugin is called by kubelet's plugin watcher upon detection // of a new registration socket opened by DRA plugin. func (h *RegistrationHandler) ValidatePlugin(pluginName string, endpoint string, versions []string) error { _, err := h.validateVersions(pluginName, versions) if err != nil { return fmt.Errorf("invalid versions of plugin %s: %w", pluginName, err) } return err } </ins>


const ( pvDeletionTimeout       = 3 * time.Minute statefulSetReadyTimeout = 3 * time.Minute <ins> taintKeyPrefix          = "zoneTaint_" </ins> ) var _ = utils.SIGDescribe("Regional PD", func() {


return multiGroupVersioner{target: gv, acceptedGroupKinds: groupKinds} } <ins> // NewCoercingMultiGroupVersioner returns the provided group version for any incoming kind. // Incoming kinds that match the provided groupKinds are preferred. // Kind may be empty in the provided group kind, in which case any kind will match. // Examples: //   gv=mygroup/__internal, groupKinds=mygroup/Foo, anothergroup/Bar //   KindForGroupVersionKinds(yetanother/v1/Baz, anothergroup/v1/Bar) -> mygroup/__internal/Bar (matched preferred group/kind) // //   gv=mygroup/__internal, groupKinds=mygroup, anothergroup //   KindForGroupVersionKinds(yetanother/v1/Baz, anothergroup/v1/Bar) -> mygroup/__internal/Bar (matched preferred group) // //   gv=mygroup/__internal, groupKinds=mygroup, anothergroup //   KindForGroupVersionKinds(yetanother/v1/Baz, yetanother/v1/Bar) -> mygroup/__internal/Baz (no preferred group/kind match, uses first kind in list) func NewCoercingMultiGroupVersioner(gv schema.GroupVersion, groupKinds ...schema.GroupKind) GroupVersioner { return multiGroupVersioner{target: gv, acceptedGroupKinds: groupKinds, coerce: true} } </ins> // KindForGroupVersionKinds returns the target group version if any kind matches any of the original group kinds. It will // use the originating kind where possible. func (v multiGroupVersioner) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool) {


// updated. The updated Endpoints object or an error will be returned. func (adapter *EndpointsAdapter) Update(namespace string, endpoints *corev1.Endpoints) (*corev1.Endpoints, error) { endpoints, err := adapter.endpointClient.Endpoints(namespace).Update(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 } <del> // ensureEndpointSliceFromEndpoints accepts a namespace and Endpoints resource // and creates or updates a corresponding EndpointSlice. The EndpointSlice // and/or an error will be returned. func (adapter *EndpointsAdapter) ensureEndpointSliceFromEndpoints(namespace string, endpoints *corev1.Endpoints) (*discovery.EndpointSlice, error) { </del> <ins> // EnsureEndpointSliceFromEndpoints accepts a namespace and Endpoints resource // and creates or updates a corresponding EndpointSlice if an endpointSliceClient // exists. An error will be returned if it fails to sync the EndpointSlice. func (adapter *EndpointsAdapter) EnsureEndpointSliceFromEndpoints(namespace string, endpoints *corev1.Endpoints) error { if adapter.endpointSliceClient == nil { return nil } </ins> endpointSlice := endpointSliceFromEndpoints(endpoints) <del> _, err := adapter.endpointSliceClient.EndpointSlices(namespace).Get(endpointSlice.Name, metav1.GetOptions{}) </del> <ins> currentEndpointSlice, err := adapter.endpointSliceClient.EndpointSlices(namespace).Get(endpointSlice.Name, metav1.GetOptions{}) </ins> if err != nil { if errors.IsNotFound(err) { <del> return adapter.endpointSliceClient.EndpointSlices(namespace).Create(endpointSlice) </del> <ins> if _, err = adapter.endpointSliceClient.EndpointSlices(namespace).Create(endpointSlice); errors.IsAlreadyExists(err) { err = nil } </ins> } <del> return nil, err </del> <ins> return err } if apiequality.Semantic.DeepEqual(currentEndpointSlice.Endpoints, endpointSlice.Endpoints) && apiequality.Semantic.DeepEqual(currentEndpointSlice.Ports, endpointSlice.Ports) && apiequality.Semantic.DeepEqual(currentEndpointSlice.Labels, endpointSlice.Labels) { return nil </ins> } <del> return adapter.endpointSliceClient.EndpointSlices(namespace).Update(endpointSlice) </del> <ins> _, err = adapter.endpointSliceClient.EndpointSlices(namespace).Update(endpointSlice) return err </ins> } // endpointSliceFromEndpoints generates an EndpointSlice from an Endpoints


import ( "fmt" <del> "strings" </del> "time" "k8s.io/kubernetes/pkg/api" <del> client "k8s.io/kubernetes/pkg/client/unversioned" </del> "k8s.io/kubernetes/pkg/util" . "github.com/onsi/ginkgo"


t.Fatalf("failed to mark all StatefulSet pods to ready: %v", err) } } <ins> // add for issue: https://github.com/kubernetes/kubernetes/issues/108837 func TestStatefulSetStatusWithPodFail(t *testing.T) { limitedPodNumber := 2 controlPlaneConfig := framework.NewIntegrationTestControlPlaneConfig() controlPlaneConfig.GenericConfig.AdmissionControl = &fakePodFailAdmission{ limitedPodNumber: limitedPodNumber, } _, s, closeFn := framework.RunAnAPIServer(controlPlaneConfig) defer closeFn() config := restclient.Config{Host: s.URL} c, err := clientset.NewForConfig(&config) if err != nil { t.Fatalf("Could not create clientset: %v", err) } resyncPeriod := 12 * time.Hour informers := informers.NewSharedInformerFactory(clientset.NewForConfigOrDie(restclient.AddUserAgent(&config, "statefulset-informers")), resyncPeriod) ssc := statefulset.NewStatefulSetController( informers.Core().V1().Pods(), informers.Apps().V1().StatefulSets(), informers.Core().V1().PersistentVolumeClaims(), informers.Apps().V1().ControllerRevisions(), clientset.NewForConfigOrDie(restclient.AddUserAgent(&config, "statefulset-controller")), ) ns := framework.CreateTestingNamespace("test-pod-fail", s, t) defer framework.DeleteTestingNamespace(ns, s, t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() informers.Start(ctx.Done()) go ssc.Run(ctx, 5) sts := newSTS("sts", ns.Name, 4) _, err = c.AppsV1().StatefulSets(sts.Namespace).Create(context.TODO(), sts, metav1.CreateOptions{}) if err != nil { t.Fatalf("Could not create statefuleSet %s: %v", sts.Name, err) } wantReplicas := limitedPodNumber var gotReplicas int32 if err := wait.PollImmediate(pollInterval, pollTimeout, func() (bool, error) { newSTS, err := c.AppsV1().StatefulSets(sts.Namespace).Get(context.TODO(), sts.Name, metav1.GetOptions{}) if err != nil { return false, err } gotReplicas = newSTS.Status.Replicas return gotReplicas == int32(wantReplicas), nil }); err != nil { t.Fatalf("StatefulSet %s status has %d replicas, want replicas %d: %v", sts.Name, gotReplicas, wantReplicas, err) } } </ins>


Name: "mypsp", }, Spec: policy.PodSecurityPolicySpec{ <ins> AllowedUnsafeSysctls: []string{"kernel.*", "net.ipv4.ip_local_port_range"}, ForbiddenSysctls:     []string{"net.ipv4.ip_default_ttl"}, </ins> SELinux: policy.SELinuxStrategyOptions{ Rule: policy.SELinuxStrategyRunAsAny, },


defer testKubelet.Cleanup() kubelet := testKubelet.kubelet pods := newTestPods(5) <ins> now := metav1.NewTime(time.Now()) </ins> pods[0].Status.Phase = v1.PodFailed pods[1].Status.Phase = v1.PodSucceeded <ins> // The pod is terminating, should not filter out. </ins> pods[2].Status.Phase = v1.PodRunning <ins> pods[2].DeletionTimestamp = &now pods[2].Status.ContainerStatuses = []v1.ContainerStatus{ {State: v1.ContainerState{ Running: &v1.ContainerStateRunning{ StartedAt: now, }, }}, } </ins> pods[3].Status.Phase = v1.PodPending <ins> pods[4].Status.Phase = v1.PodRunning </ins> expected := []*v1.Pod{pods[2], pods[3], pods[4]} kubelet.podManager.SetPods(pods)