diff --git a/staging/src/k8s.io/kubectl/pkg/util/pod_port.go b/staging/src/k8s.io/kubectl/pkg/util/pod_port.go index 6d78501a89a..bcd2c728184 100644 --- a/staging/src/k8s.io/kubectl/pkg/util/pod_port.go +++ b/staging/src/k8s.io/kubectl/pkg/util/pod_port.go @@ -31,6 +31,12 @@ func LookupContainerPortNumberByName(pod v1.Pod, name string) (int32, error) { } } } - + for _, ctr := range pod.Spec.InitContainers { + for _, ctrportspec := range ctr.Ports { + if ctrportspec.Name == name { + return ctrportspec.ContainerPort, nil + } + } + } return int32(-1), fmt.Errorf("Pod '%s' does not have a named port '%s'", pod.Name, name) } diff --git a/staging/src/k8s.io/kubectl/pkg/util/pod_port_test.go b/staging/src/k8s.io/kubectl/pkg/util/pod_port_test.go index cecf515161c..cd8fa47542a 100644 --- a/staging/src/k8s.io/kubectl/pkg/util/pod_port_test.go +++ b/staging/src/k8s.io/kubectl/pkg/util/pod_port_test.go @@ -71,6 +71,67 @@ func TestLookupContainerPortNumberByName(t *testing.T) { portnum: int32(0), err: true, }, + { + name: "test success 2", + pod: v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ + { + Ports: []v1.ContainerPort{ + { + Name: "https", + ContainerPort: int32(443)}, + { + Name: "http", + ContainerPort: int32(80)}, + }, + }, + }, + InitContainers: []v1.Container{ + { + Ports: []v1.ContainerPort{ + { + Name: "sql", + ContainerPort: int32(3306)}, + }, + }, + }, + }, + }, + portname: "sql", + portnum: int32(3306), + err: false, + }, { + name: "test failure 2", + pod: v1.Pod{ + Spec: v1.PodSpec{ + Containers: []v1.Container{ + { + Ports: []v1.ContainerPort{ + { + Name: "https", + ContainerPort: int32(443)}, + { + Name: "http", + ContainerPort: int32(80)}, + }, + }, + }, + InitContainers: []v1.Container{ + { + Ports: []v1.ContainerPort{ + { + Name: "sql", + ContainerPort: int32(3306)}, + }, + }, + }, + }, + }, + portname: "metrics", + portnum: int32(0), + err: true, + }, } for _, tt := range tests {