123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809 |
- /*
- Copyright 2015 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 pod
- import (
- "reflect"
- "strings"
- "testing"
- "time"
- "github.com/stretchr/testify/assert"
- v1 "k8s.io/api/core/v1"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/util/intstr"
- "k8s.io/apimachinery/pkg/util/sets"
- "k8s.io/apimachinery/pkg/util/validation/field"
- utilfeature "k8s.io/apiserver/pkg/util/feature"
- featuregatetesting "k8s.io/component-base/featuregate/testing"
- "k8s.io/kubernetes/pkg/features"
- )
- func TestFindPort(t *testing.T) {
- testCases := []struct {
- name string
- containers []v1.Container
- port intstr.IntOrString
- expected int
- pass bool
- }{{
- name: "valid int, no ports",
- containers: []v1.Container{{}},
- port: intstr.FromInt(93),
- expected: 93,
- pass: true,
- }, {
- name: "valid int, with ports",
- containers: []v1.Container{{Ports: []v1.ContainerPort{{
- Name: "",
- ContainerPort: 11,
- Protocol: "TCP",
- }, {
- Name: "p",
- ContainerPort: 22,
- Protocol: "TCP",
- }}}},
- port: intstr.FromInt(93),
- expected: 93,
- pass: true,
- }, {
- name: "valid str, no ports",
- containers: []v1.Container{{}},
- port: intstr.FromString("p"),
- expected: 0,
- pass: false,
- }, {
- name: "valid str, one ctr with ports",
- containers: []v1.Container{{Ports: []v1.ContainerPort{{
- Name: "",
- ContainerPort: 11,
- Protocol: "UDP",
- }, {
- Name: "p",
- ContainerPort: 22,
- Protocol: "TCP",
- }, {
- Name: "q",
- ContainerPort: 33,
- Protocol: "TCP",
- }}}},
- port: intstr.FromString("q"),
- expected: 33,
- pass: true,
- }, {
- name: "valid str, two ctr with ports",
- containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{
- Name: "",
- ContainerPort: 11,
- Protocol: "UDP",
- }, {
- Name: "p",
- ContainerPort: 22,
- Protocol: "TCP",
- }, {
- Name: "q",
- ContainerPort: 33,
- Protocol: "TCP",
- }}}},
- port: intstr.FromString("q"),
- expected: 33,
- pass: true,
- }, {
- name: "valid str, two ctr with same port",
- containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{
- Name: "",
- ContainerPort: 11,
- Protocol: "UDP",
- }, {
- Name: "p",
- ContainerPort: 22,
- Protocol: "TCP",
- }, {
- Name: "q",
- ContainerPort: 22,
- Protocol: "TCP",
- }}}},
- port: intstr.FromString("q"),
- expected: 22,
- pass: true,
- }, {
- name: "valid str, invalid protocol",
- containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{
- Name: "a",
- ContainerPort: 11,
- Protocol: "snmp",
- },
- }}},
- port: intstr.FromString("a"),
- expected: 0,
- pass: false,
- }, {
- name: "valid hostPort",
- containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{
- Name: "a",
- ContainerPort: 11,
- HostPort: 81,
- Protocol: "TCP",
- },
- }}},
- port: intstr.FromString("a"),
- expected: 11,
- pass: true,
- },
- {
- name: "invalid hostPort",
- containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{
- Name: "a",
- ContainerPort: 11,
- HostPort: -1,
- Protocol: "TCP",
- },
- }}},
- port: intstr.FromString("a"),
- expected: 11,
- pass: true,
- //this should fail but passes.
- },
- {
- name: "invalid ContainerPort",
- containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{
- Name: "a",
- ContainerPort: -1,
- Protocol: "TCP",
- },
- }}},
- port: intstr.FromString("a"),
- expected: -1,
- pass: true,
- //this should fail but passes
- },
- {
- name: "HostIP Address",
- containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{
- Name: "a",
- ContainerPort: 11,
- HostIP: "192.168.1.1",
- Protocol: "TCP",
- },
- }}},
- port: intstr.FromString("a"),
- expected: 11,
- pass: true,
- },
- }
- for _, tc := range testCases {
- port, err := FindPort(&v1.Pod{Spec: v1.PodSpec{Containers: tc.containers}},
- &v1.ServicePort{Protocol: "TCP", TargetPort: tc.port})
- if err != nil && tc.pass {
- t.Errorf("unexpected error for %s: %v", tc.name, err)
- }
- if err == nil && !tc.pass {
- t.Errorf("unexpected non-error for %s: %d", tc.name, port)
- }
- if port != tc.expected {
- t.Errorf("wrong result for %s: expected %d, got %d", tc.name, tc.expected, port)
- }
- }
- }
- func TestVisitContainers(t *testing.T) {
- defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.EphemeralContainers, true)()
- testCases := []struct {
- description string
- haveSpec *v1.PodSpec
- wantNames []string
- }{
- {
- "empty podspec",
- &v1.PodSpec{},
- []string{},
- },
- {
- "regular containers",
- &v1.PodSpec{
- Containers: []v1.Container{
- {Name: "c1"},
- {Name: "c2"},
- },
- },
- []string{"c1", "c2"},
- },
- {
- "init containers",
- &v1.PodSpec{
- InitContainers: []v1.Container{
- {Name: "i1"},
- {Name: "i2"},
- },
- },
- []string{"i1", "i2"},
- },
- {
- "regular and init containers",
- &v1.PodSpec{
- Containers: []v1.Container{
- {Name: "c1"},
- {Name: "c2"},
- },
- InitContainers: []v1.Container{
- {Name: "i1"},
- {Name: "i2"},
- },
- },
- []string{"i1", "i2", "c1", "c2"},
- },
- {
- "ephemeral containers",
- &v1.PodSpec{
- Containers: []v1.Container{
- {Name: "c1"},
- {Name: "c2"},
- },
- EphemeralContainers: []v1.EphemeralContainer{
- {EphemeralContainerCommon: v1.EphemeralContainerCommon{Name: "e1"}},
- },
- },
- []string{"c1", "c2", "e1"},
- },
- {
- "all container types",
- &v1.PodSpec{
- Containers: []v1.Container{
- {Name: "c1"},
- {Name: "c2"},
- },
- InitContainers: []v1.Container{
- {Name: "i1"},
- {Name: "i2"},
- },
- EphemeralContainers: []v1.EphemeralContainer{
- {EphemeralContainerCommon: v1.EphemeralContainerCommon{Name: "e1"}},
- {EphemeralContainerCommon: v1.EphemeralContainerCommon{Name: "e2"}},
- },
- },
- []string{"i1", "i2", "c1", "c2", "e1", "e2"},
- },
- {
- "dropping fields",
- &v1.PodSpec{
- Containers: []v1.Container{
- {Name: "c1"},
- {Name: "c2", SecurityContext: &v1.SecurityContext{}},
- },
- InitContainers: []v1.Container{
- {Name: "i1"},
- {Name: "i2", SecurityContext: &v1.SecurityContext{}},
- },
- EphemeralContainers: []v1.EphemeralContainer{
- {EphemeralContainerCommon: v1.EphemeralContainerCommon{Name: "e1"}},
- {EphemeralContainerCommon: v1.EphemeralContainerCommon{Name: "e2", SecurityContext: &v1.SecurityContext{}}},
- },
- },
- []string{"i1", "i2", "c1", "c2", "e1", "e2"},
- },
- }
- for _, tc := range testCases {
- gotNames := []string{}
- VisitContainers(tc.haveSpec, func(c *v1.Container) bool {
- gotNames = append(gotNames, c.Name)
- if c.SecurityContext != nil {
- c.SecurityContext = nil
- }
- return true
- })
- if !reflect.DeepEqual(gotNames, tc.wantNames) {
- t.Errorf("VisitContainers() for test case %q visited containers %q, wanted to visit %q", tc.description, gotNames, tc.wantNames)
- }
- for _, c := range tc.haveSpec.Containers {
- if c.SecurityContext != nil {
- t.Errorf("VisitContainers() for test case %q: got SecurityContext %#v for container %v, wanted nil", tc.description, c.SecurityContext, c.Name)
- }
- }
- for _, c := range tc.haveSpec.InitContainers {
- if c.SecurityContext != nil {
- t.Errorf("VisitContainers() for test case %q: got SecurityContext %#v for init container %v, wanted nil", tc.description, c.SecurityContext, c.Name)
- }
- }
- for _, c := range tc.haveSpec.EphemeralContainers {
- if c.SecurityContext != nil {
- t.Errorf("VisitContainers() for test case %q: got SecurityContext %#v for ephemeral container %v, wanted nil", tc.description, c.SecurityContext, c.Name)
- }
- }
- }
- }
- func TestPodSecrets(t *testing.T) {
- defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.EphemeralContainers, true)()
- // Stub containing all possible secret references in a pod.
- // The names of the referenced secrets match struct paths detected by reflection.
- pod := &v1.Pod{
- Spec: v1.PodSpec{
- Containers: []v1.Container{{
- EnvFrom: []v1.EnvFromSource{{
- SecretRef: &v1.SecretEnvSource{
- LocalObjectReference: v1.LocalObjectReference{
- Name: "Spec.Containers[*].EnvFrom[*].SecretRef"}}}},
- Env: []v1.EnvVar{{
- ValueFrom: &v1.EnvVarSource{
- SecretKeyRef: &v1.SecretKeySelector{
- LocalObjectReference: v1.LocalObjectReference{
- Name: "Spec.Containers[*].Env[*].ValueFrom.SecretKeyRef"}}}}}}},
- ImagePullSecrets: []v1.LocalObjectReference{{
- Name: "Spec.ImagePullSecrets"}},
- InitContainers: []v1.Container{{
- EnvFrom: []v1.EnvFromSource{{
- SecretRef: &v1.SecretEnvSource{
- LocalObjectReference: v1.LocalObjectReference{
- Name: "Spec.InitContainers[*].EnvFrom[*].SecretRef"}}}},
- Env: []v1.EnvVar{{
- ValueFrom: &v1.EnvVarSource{
- SecretKeyRef: &v1.SecretKeySelector{
- LocalObjectReference: v1.LocalObjectReference{
- Name: "Spec.InitContainers[*].Env[*].ValueFrom.SecretKeyRef"}}}}}}},
- Volumes: []v1.Volume{{
- VolumeSource: v1.VolumeSource{
- AzureFile: &v1.AzureFileVolumeSource{
- SecretName: "Spec.Volumes[*].VolumeSource.AzureFile.SecretName"}}}, {
- VolumeSource: v1.VolumeSource{
- CephFS: &v1.CephFSVolumeSource{
- SecretRef: &v1.LocalObjectReference{
- Name: "Spec.Volumes[*].VolumeSource.CephFS.SecretRef"}}}}, {
- VolumeSource: v1.VolumeSource{
- Cinder: &v1.CinderVolumeSource{
- SecretRef: &v1.LocalObjectReference{
- Name: "Spec.Volumes[*].VolumeSource.Cinder.SecretRef"}}}}, {
- VolumeSource: v1.VolumeSource{
- FlexVolume: &v1.FlexVolumeSource{
- SecretRef: &v1.LocalObjectReference{
- Name: "Spec.Volumes[*].VolumeSource.FlexVolume.SecretRef"}}}}, {
- VolumeSource: v1.VolumeSource{
- Projected: &v1.ProjectedVolumeSource{
- Sources: []v1.VolumeProjection{{
- Secret: &v1.SecretProjection{
- LocalObjectReference: v1.LocalObjectReference{
- Name: "Spec.Volumes[*].VolumeSource.Projected.Sources[*].Secret"}}}}}}}, {
- VolumeSource: v1.VolumeSource{
- RBD: &v1.RBDVolumeSource{
- SecretRef: &v1.LocalObjectReference{
- Name: "Spec.Volumes[*].VolumeSource.RBD.SecretRef"}}}}, {
- VolumeSource: v1.VolumeSource{
- Secret: &v1.SecretVolumeSource{
- SecretName: "Spec.Volumes[*].VolumeSource.Secret.SecretName"}}}, {
- VolumeSource: v1.VolumeSource{
- Secret: &v1.SecretVolumeSource{
- SecretName: "Spec.Volumes[*].VolumeSource.Secret"}}}, {
- VolumeSource: v1.VolumeSource{
- ScaleIO: &v1.ScaleIOVolumeSource{
- SecretRef: &v1.LocalObjectReference{
- Name: "Spec.Volumes[*].VolumeSource.ScaleIO.SecretRef"}}}}, {
- VolumeSource: v1.VolumeSource{
- ISCSI: &v1.ISCSIVolumeSource{
- SecretRef: &v1.LocalObjectReference{
- Name: "Spec.Volumes[*].VolumeSource.ISCSI.SecretRef"}}}}, {
- VolumeSource: v1.VolumeSource{
- StorageOS: &v1.StorageOSVolumeSource{
- SecretRef: &v1.LocalObjectReference{
- Name: "Spec.Volumes[*].VolumeSource.StorageOS.SecretRef"}}}}, {
- VolumeSource: v1.VolumeSource{
- CSI: &v1.CSIVolumeSource{
- NodePublishSecretRef: &v1.LocalObjectReference{
- Name: "Spec.Volumes[*].VolumeSource.CSI.NodePublishSecretRef"}}}}},
- EphemeralContainers: []v1.EphemeralContainer{{
- EphemeralContainerCommon: v1.EphemeralContainerCommon{
- EnvFrom: []v1.EnvFromSource{{
- SecretRef: &v1.SecretEnvSource{
- LocalObjectReference: v1.LocalObjectReference{
- Name: "Spec.EphemeralContainers[*].EphemeralContainerCommon.EnvFrom[*].SecretRef"}}}},
- Env: []v1.EnvVar{{
- ValueFrom: &v1.EnvVarSource{
- SecretKeyRef: &v1.SecretKeySelector{
- LocalObjectReference: v1.LocalObjectReference{
- Name: "Spec.EphemeralContainers[*].EphemeralContainerCommon.Env[*].ValueFrom.SecretKeyRef"}}}}}}}},
- },
- }
- extractedNames := sets.NewString()
- VisitPodSecretNames(pod, func(name string) bool {
- extractedNames.Insert(name)
- return true
- })
- // excludedSecretPaths holds struct paths to fields with "secret" in the name that are not actually references to secret API objects
- excludedSecretPaths := sets.NewString(
- "Spec.Volumes[*].VolumeSource.CephFS.SecretFile",
- )
- // expectedSecretPaths holds struct paths to fields with "secret" in the name that are references to secret API objects.
- // every path here should be represented as an example in the Pod stub above, with the secret name set to the path.
- expectedSecretPaths := sets.NewString(
- "Spec.Containers[*].EnvFrom[*].SecretRef",
- "Spec.Containers[*].Env[*].ValueFrom.SecretKeyRef",
- "Spec.EphemeralContainers[*].EphemeralContainerCommon.EnvFrom[*].SecretRef",
- "Spec.EphemeralContainers[*].EphemeralContainerCommon.Env[*].ValueFrom.SecretKeyRef",
- "Spec.ImagePullSecrets",
- "Spec.InitContainers[*].EnvFrom[*].SecretRef",
- "Spec.InitContainers[*].Env[*].ValueFrom.SecretKeyRef",
- "Spec.Volumes[*].VolumeSource.AzureFile.SecretName",
- "Spec.Volumes[*].VolumeSource.CephFS.SecretRef",
- "Spec.Volumes[*].VolumeSource.Cinder.SecretRef",
- "Spec.Volumes[*].VolumeSource.FlexVolume.SecretRef",
- "Spec.Volumes[*].VolumeSource.Projected.Sources[*].Secret",
- "Spec.Volumes[*].VolumeSource.RBD.SecretRef",
- "Spec.Volumes[*].VolumeSource.Secret",
- "Spec.Volumes[*].VolumeSource.Secret.SecretName",
- "Spec.Volumes[*].VolumeSource.ScaleIO.SecretRef",
- "Spec.Volumes[*].VolumeSource.ISCSI.SecretRef",
- "Spec.Volumes[*].VolumeSource.StorageOS.SecretRef",
- "Spec.Volumes[*].VolumeSource.CSI.NodePublishSecretRef",
- )
- secretPaths := collectResourcePaths(t, "secret", nil, "", reflect.TypeOf(&v1.Pod{}))
- secretPaths = secretPaths.Difference(excludedSecretPaths)
- if missingPaths := expectedSecretPaths.Difference(secretPaths); len(missingPaths) > 0 {
- t.Logf("Missing expected secret paths:\n%s", strings.Join(missingPaths.List(), "\n"))
- t.Error("Missing expected secret paths. Verify VisitPodSecretNames() is correctly finding the missing paths, then correct expectedSecretPaths")
- }
- if extraPaths := secretPaths.Difference(expectedSecretPaths); len(extraPaths) > 0 {
- t.Logf("Extra secret paths:\n%s", strings.Join(extraPaths.List(), "\n"))
- t.Error("Extra fields with 'secret' in the name found. Verify VisitPodSecretNames() is including these fields if appropriate, then correct expectedSecretPaths")
- }
- if missingNames := expectedSecretPaths.Difference(extractedNames); len(missingNames) > 0 {
- t.Logf("Missing expected secret names:\n%s", strings.Join(missingNames.List(), "\n"))
- t.Error("Missing expected secret names. Verify the pod stub above includes these references, then verify VisitPodSecretNames() is correctly finding the missing names")
- }
- if extraNames := extractedNames.Difference(expectedSecretPaths); len(extraNames) > 0 {
- t.Logf("Extra secret names:\n%s", strings.Join(extraNames.List(), "\n"))
- t.Error("Extra secret names extracted. Verify VisitPodSecretNames() is correctly extracting secret names")
- }
- }
- // collectResourcePaths traverses the object, computing all the struct paths that lead to fields with resourcename in the name.
- func collectResourcePaths(t *testing.T, resourcename string, path *field.Path, name string, tp reflect.Type) sets.String {
- resourcename = strings.ToLower(resourcename)
- resourcePaths := sets.NewString()
- if tp.Kind() == reflect.Ptr {
- resourcePaths.Insert(collectResourcePaths(t, resourcename, path, name, tp.Elem()).List()...)
- return resourcePaths
- }
- if strings.Contains(strings.ToLower(name), resourcename) {
- resourcePaths.Insert(path.String())
- }
- switch tp.Kind() {
- case reflect.Ptr:
- resourcePaths.Insert(collectResourcePaths(t, resourcename, path, name, tp.Elem()).List()...)
- case reflect.Struct:
- // ObjectMeta is generic and therefore should never have a field with a specific resource's name;
- // it contains cycles so it's easiest to just skip it.
- if name == "ObjectMeta" {
- break
- }
- for i := 0; i < tp.NumField(); i++ {
- field := tp.Field(i)
- resourcePaths.Insert(collectResourcePaths(t, resourcename, path.Child(field.Name), field.Name, field.Type).List()...)
- }
- case reflect.Interface:
- t.Errorf("cannot find %s fields in interface{} field %s", resourcename, path.String())
- case reflect.Map:
- resourcePaths.Insert(collectResourcePaths(t, resourcename, path.Key("*"), "", tp.Elem()).List()...)
- case reflect.Slice:
- resourcePaths.Insert(collectResourcePaths(t, resourcename, path.Key("*"), "", tp.Elem()).List()...)
- default:
- // all primitive types
- }
- return resourcePaths
- }
- func TestPodConfigmaps(t *testing.T) {
- defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.EphemeralContainers, true)()
- // Stub containing all possible ConfigMap references in a pod.
- // The names of the referenced ConfigMaps match struct paths detected by reflection.
- pod := &v1.Pod{
- Spec: v1.PodSpec{
- Containers: []v1.Container{{
- EnvFrom: []v1.EnvFromSource{{
- ConfigMapRef: &v1.ConfigMapEnvSource{
- LocalObjectReference: v1.LocalObjectReference{
- Name: "Spec.Containers[*].EnvFrom[*].ConfigMapRef"}}}},
- Env: []v1.EnvVar{{
- ValueFrom: &v1.EnvVarSource{
- ConfigMapKeyRef: &v1.ConfigMapKeySelector{
- LocalObjectReference: v1.LocalObjectReference{
- Name: "Spec.Containers[*].Env[*].ValueFrom.ConfigMapKeyRef"}}}}}}},
- EphemeralContainers: []v1.EphemeralContainer{{
- EphemeralContainerCommon: v1.EphemeralContainerCommon{
- EnvFrom: []v1.EnvFromSource{{
- ConfigMapRef: &v1.ConfigMapEnvSource{
- LocalObjectReference: v1.LocalObjectReference{
- Name: "Spec.EphemeralContainers[*].EphemeralContainerCommon.EnvFrom[*].ConfigMapRef"}}}},
- Env: []v1.EnvVar{{
- ValueFrom: &v1.EnvVarSource{
- ConfigMapKeyRef: &v1.ConfigMapKeySelector{
- LocalObjectReference: v1.LocalObjectReference{
- Name: "Spec.EphemeralContainers[*].EphemeralContainerCommon.Env[*].ValueFrom.ConfigMapKeyRef"}}}}}}}},
- InitContainers: []v1.Container{{
- EnvFrom: []v1.EnvFromSource{{
- ConfigMapRef: &v1.ConfigMapEnvSource{
- LocalObjectReference: v1.LocalObjectReference{
- Name: "Spec.InitContainers[*].EnvFrom[*].ConfigMapRef"}}}},
- Env: []v1.EnvVar{{
- ValueFrom: &v1.EnvVarSource{
- ConfigMapKeyRef: &v1.ConfigMapKeySelector{
- LocalObjectReference: v1.LocalObjectReference{
- Name: "Spec.InitContainers[*].Env[*].ValueFrom.ConfigMapKeyRef"}}}}}}},
- Volumes: []v1.Volume{{
- VolumeSource: v1.VolumeSource{
- Projected: &v1.ProjectedVolumeSource{
- Sources: []v1.VolumeProjection{{
- ConfigMap: &v1.ConfigMapProjection{
- LocalObjectReference: v1.LocalObjectReference{
- Name: "Spec.Volumes[*].VolumeSource.Projected.Sources[*].ConfigMap"}}}}}}}, {
- VolumeSource: v1.VolumeSource{
- ConfigMap: &v1.ConfigMapVolumeSource{
- LocalObjectReference: v1.LocalObjectReference{
- Name: "Spec.Volumes[*].VolumeSource.ConfigMap"}}}}},
- },
- }
- extractedNames := sets.NewString()
- VisitPodConfigmapNames(pod, func(name string) bool {
- extractedNames.Insert(name)
- return true
- })
- // expectedPaths holds struct paths to fields with "ConfigMap" in the name that are references to ConfigMap API objects.
- // every path here should be represented as an example in the Pod stub above, with the ConfigMap name set to the path.
- expectedPaths := sets.NewString(
- "Spec.Containers[*].EnvFrom[*].ConfigMapRef",
- "Spec.Containers[*].Env[*].ValueFrom.ConfigMapKeyRef",
- "Spec.EphemeralContainers[*].EphemeralContainerCommon.EnvFrom[*].ConfigMapRef",
- "Spec.EphemeralContainers[*].EphemeralContainerCommon.Env[*].ValueFrom.ConfigMapKeyRef",
- "Spec.InitContainers[*].EnvFrom[*].ConfigMapRef",
- "Spec.InitContainers[*].Env[*].ValueFrom.ConfigMapKeyRef",
- "Spec.Volumes[*].VolumeSource.Projected.Sources[*].ConfigMap",
- "Spec.Volumes[*].VolumeSource.ConfigMap",
- )
- collectPaths := collectResourcePaths(t, "ConfigMap", nil, "", reflect.TypeOf(&v1.Pod{}))
- if missingPaths := expectedPaths.Difference(collectPaths); len(missingPaths) > 0 {
- t.Logf("Missing expected paths:\n%s", strings.Join(missingPaths.List(), "\n"))
- t.Error("Missing expected paths. Verify VisitPodConfigmapNames() is correctly finding the missing paths, then correct expectedPaths")
- }
- if extraPaths := collectPaths.Difference(expectedPaths); len(extraPaths) > 0 {
- t.Logf("Extra paths:\n%s", strings.Join(extraPaths.List(), "\n"))
- t.Error("Extra fields with resource in the name found. Verify VisitPodConfigmapNames() is including these fields if appropriate, then correct expectedPaths")
- }
- if missingNames := expectedPaths.Difference(extractedNames); len(missingNames) > 0 {
- t.Logf("Missing expected names:\n%s", strings.Join(missingNames.List(), "\n"))
- t.Error("Missing expected names. Verify the pod stub above includes these references, then verify VisitPodConfigmapNames() is correctly finding the missing names")
- }
- if extraNames := extractedNames.Difference(expectedPaths); len(extraNames) > 0 {
- t.Logf("Extra names:\n%s", strings.Join(extraNames.List(), "\n"))
- t.Error("Extra names extracted. Verify VisitPodConfigmapNames() is correctly extracting resource names")
- }
- }
- func newPod(now metav1.Time, ready bool, beforeSec int) *v1.Pod {
- conditionStatus := v1.ConditionFalse
- if ready {
- conditionStatus = v1.ConditionTrue
- }
- return &v1.Pod{
- Status: v1.PodStatus{
- Conditions: []v1.PodCondition{
- {
- Type: v1.PodReady,
- LastTransitionTime: metav1.NewTime(now.Time.Add(-1 * time.Duration(beforeSec) * time.Second)),
- Status: conditionStatus,
- },
- },
- },
- }
- }
- func TestIsPodAvailable(t *testing.T) {
- now := metav1.Now()
- tests := []struct {
- pod *v1.Pod
- minReadySeconds int32
- expected bool
- }{
- {
- pod: newPod(now, false, 0),
- minReadySeconds: 0,
- expected: false,
- },
- {
- pod: newPod(now, true, 0),
- minReadySeconds: 1,
- expected: false,
- },
- {
- pod: newPod(now, true, 0),
- minReadySeconds: 0,
- expected: true,
- },
- {
- pod: newPod(now, true, 51),
- minReadySeconds: 50,
- expected: true,
- },
- }
- for i, test := range tests {
- isAvailable := IsPodAvailable(test.pod, test.minReadySeconds, now)
- if isAvailable != test.expected {
- t.Errorf("[tc #%d] expected available pod: %t, got: %t", i, test.expected, isAvailable)
- }
- }
- }
- func TestGetContainerStatus(t *testing.T) {
- type ExpectedStruct struct {
- status v1.ContainerStatus
- exists bool
- }
- tests := []struct {
- status []v1.ContainerStatus
- name string
- expected ExpectedStruct
- desc string
- }{
- {
- status: []v1.ContainerStatus{{Name: "test1", Ready: false, Image: "image1"}, {Name: "test2", Ready: true, Image: "image1"}},
- name: "test1",
- expected: ExpectedStruct{status: v1.ContainerStatus{Name: "test1", Ready: false, Image: "image1"}, exists: true},
- desc: "retrieve ContainerStatus with Name=\"test1\"",
- },
- {
- status: []v1.ContainerStatus{{Name: "test2", Ready: false, Image: "image2"}},
- name: "test1",
- expected: ExpectedStruct{status: v1.ContainerStatus{}, exists: false},
- desc: "no matching ContainerStatus with Name=\"test1\"",
- },
- {
- status: []v1.ContainerStatus{{Name: "test3", Ready: false, Image: "image3"}},
- name: "",
- expected: ExpectedStruct{status: v1.ContainerStatus{}, exists: false},
- desc: "retrieve an empty ContainerStatus with container name empty",
- },
- {
- status: nil,
- name: "",
- expected: ExpectedStruct{status: v1.ContainerStatus{}, exists: false},
- desc: "retrieve an empty ContainerStatus with status nil",
- },
- }
- for _, test := range tests {
- resultStatus, exists := GetContainerStatus(test.status, test.name)
- assert.Equal(t, test.expected.status, resultStatus, "GetContainerStatus: "+test.desc)
- assert.Equal(t, test.expected.exists, exists, "GetContainerStatus: "+test.desc)
- resultStatus = GetExistingContainerStatus(test.status, test.name)
- assert.Equal(t, test.expected.status, resultStatus, "GetExistingContainerStatus: "+test.desc)
- }
- }
- func TestUpdatePodCondition(t *testing.T) {
- time := metav1.Now()
- podStatus := v1.PodStatus{
- Conditions: []v1.PodCondition{
- {
- Type: v1.PodReady,
- Status: v1.ConditionTrue,
- Reason: "successfully",
- Message: "sync pod successfully",
- LastProbeTime: time,
- LastTransitionTime: metav1.NewTime(time.Add(1000)),
- },
- },
- }
- tests := []struct {
- status *v1.PodStatus
- conditions v1.PodCondition
- expected bool
- desc string
- }{
- {
- status: &podStatus,
- conditions: v1.PodCondition{
- Type: v1.PodReady,
- Status: v1.ConditionTrue,
- Reason: "successfully",
- Message: "sync pod successfully",
- LastProbeTime: time,
- LastTransitionTime: metav1.NewTime(time.Add(1000))},
- expected: false,
- desc: "all equal, no update",
- },
- {
- status: &podStatus,
- conditions: v1.PodCondition{
- Type: v1.PodScheduled,
- Status: v1.ConditionTrue,
- Reason: "successfully",
- Message: "sync pod successfully",
- LastProbeTime: time,
- LastTransitionTime: metav1.NewTime(time.Add(1000))},
- expected: true,
- desc: "not equal Type, should get updated",
- },
- {
- status: &podStatus,
- conditions: v1.PodCondition{
- Type: v1.PodReady,
- Status: v1.ConditionFalse,
- Reason: "successfully",
- Message: "sync pod successfully",
- LastProbeTime: time,
- LastTransitionTime: metav1.NewTime(time.Add(1000))},
- expected: true,
- desc: "not equal Status, should get updated",
- },
- }
- for _, test := range tests {
- resultStatus := UpdatePodCondition(test.status, &test.conditions)
- assert.Equal(t, test.expected, resultStatus, test.desc)
- }
- }
- // TestGetPodPriority tests GetPodPriority function.
- func TestGetPodPriority(t *testing.T) {
- p := int32(20)
- tests := []struct {
- name string
- pod *v1.Pod
- expectedPriority int32
- }{
- {
- name: "no priority pod resolves to static default priority",
- pod: &v1.Pod{
- Spec: v1.PodSpec{Containers: []v1.Container{
- {Name: "container", Image: "image"}},
- },
- },
- expectedPriority: 0,
- },
- {
- name: "pod with priority resolves correctly",
- pod: &v1.Pod{
- Spec: v1.PodSpec{Containers: []v1.Container{
- {Name: "container", Image: "image"}},
- Priority: &p,
- },
- },
- expectedPriority: p,
- },
- }
- for _, test := range tests {
- if GetPodPriority(test.pod) != test.expectedPriority {
- t.Errorf("expected pod priority: %v, got %v", test.expectedPriority, GetPodPriority(test.pod))
- }
- }
- }
|