Fix named ports of restartable init containers don't propagate to EndpointSlice

This commit is contained in:
Tsubasa Nagasawa 2024-11-19 13:43:07 +09:00
parent a6e995379a
commit e637659d89
2 changed files with 57 additions and 0 deletions

View File

@ -392,6 +392,17 @@ func findPort(pod *v1.Pod, svcPort *v1.ServicePort) (int, error) {
}
}
}
// also support sidecar container (initContainer with restartPolicy=Always)
for _, container := range pod.Spec.InitContainers {
if container.RestartPolicy == nil || *container.RestartPolicy != v1.ContainerRestartPolicyAlways {
continue
}
for _, port := range container.Ports {
if port.Name == name && port.Protocol == svcPort.Protocol {
return int(port.ContainerPort), nil
}
}
}
case intstr.Int:
return portName.IntValue(), nil
}

View File

@ -515,6 +515,7 @@ func TestServiceControllerKey(t *testing.T) {
func TestGetEndpointPorts(t *testing.T) {
protoTCP := v1.ProtocolTCP
restartPolicyAlways := v1.ContainerRestartPolicyAlways
testCases := map[string]struct {
service *v1.Service
@ -585,6 +586,51 @@ func TestGetEndpointPorts(t *testing.T) {
AppProtocol: pointer.String("https"),
}},
},
"service with named port for restartable init container": {
service: &v1.Service{
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http-sidecar",
Port: 8080,
TargetPort: intstr.FromInt32(8080),
Protocol: protoTCP,
}, {
Name: "http",
Port: 8090,
TargetPort: intstr.FromString("http"),
Protocol: protoTCP,
}},
},
},
pod: &v1.Pod{
Spec: v1.PodSpec{
InitContainers: []v1.Container{{
Ports: []v1.ContainerPort{{
Name: "http-sidecar",
ContainerPort: int32(8080),
Protocol: protoTCP,
}},
RestartPolicy: &restartPolicyAlways,
}},
Containers: []v1.Container{{
Ports: []v1.ContainerPort{{
Name: "http",
ContainerPort: int32(8090),
Protocol: protoTCP,
}},
}},
},
},
expectedPorts: []*discovery.EndpointPort{{
Name: pointer.String("http-sidecar"),
Port: pointer.Int32(8080),
Protocol: &protoTCP,
}, {
Name: pointer.String("http"),
Port: pointer.Int32(8090),
Protocol: &protoTCP,
}},
},
}
for name, tc := range testCases {