Skip to content

Commit e637659

Browse files
committed
Fix named ports of restartable init containers don't propagate to EndpointSlice
1 parent a6e9953 commit e637659

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

staging/src/k8s.io/endpointslice/utils.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,17 @@ func findPort(pod *v1.Pod, svcPort *v1.ServicePort) (int, error) {
392392
}
393393
}
394394
}
395+
// also support sidecar container (initContainer with restartPolicy=Always)
396+
for _, container := range pod.Spec.InitContainers {
397+
if container.RestartPolicy == nil || *container.RestartPolicy != v1.ContainerRestartPolicyAlways {
398+
continue
399+
}
400+
for _, port := range container.Ports {
401+
if port.Name == name && port.Protocol == svcPort.Protocol {
402+
return int(port.ContainerPort), nil
403+
}
404+
}
405+
}
395406
case intstr.Int:
396407
return portName.IntValue(), nil
397408
}

staging/src/k8s.io/endpointslice/utils_test.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -515,6 +515,7 @@ func TestServiceControllerKey(t *testing.T) {
515515

516516
func TestGetEndpointPorts(t *testing.T) {
517517
protoTCP := v1.ProtocolTCP
518+
restartPolicyAlways := v1.ContainerRestartPolicyAlways
518519

519520
testCases := map[string]struct {
520521
service *v1.Service
@@ -585,6 +586,51 @@ func TestGetEndpointPorts(t *testing.T) {
585586
AppProtocol: pointer.String("https"),
586587
}},
587588
},
589+
"service with named port for restartable init container": {
590+
service: &v1.Service{
591+
Spec: v1.ServiceSpec{
592+
Ports: []v1.ServicePort{{
593+
Name: "http-sidecar",
594+
Port: 8080,
595+
TargetPort: intstr.FromInt32(8080),
596+
Protocol: protoTCP,
597+
}, {
598+
Name: "http",
599+
Port: 8090,
600+
TargetPort: intstr.FromString("http"),
601+
Protocol: protoTCP,
602+
}},
603+
},
604+
},
605+
pod: &v1.Pod{
606+
Spec: v1.PodSpec{
607+
InitContainers: []v1.Container{{
608+
Ports: []v1.ContainerPort{{
609+
Name: "http-sidecar",
610+
ContainerPort: int32(8080),
611+
Protocol: protoTCP,
612+
}},
613+
RestartPolicy: &restartPolicyAlways,
614+
}},
615+
Containers: []v1.Container{{
616+
Ports: []v1.ContainerPort{{
617+
Name: "http",
618+
ContainerPort: int32(8090),
619+
Protocol: protoTCP,
620+
}},
621+
}},
622+
},
623+
},
624+
expectedPorts: []*discovery.EndpointPort{{
625+
Name: pointer.String("http-sidecar"),
626+
Port: pointer.Int32(8080),
627+
Protocol: &protoTCP,
628+
}, {
629+
Name: pointer.String("http"),
630+
Port: pointer.Int32(8090),
631+
Protocol: &protoTCP,
632+
}},
633+
},
588634
}
589635

590636
for name, tc := range testCases {

0 commit comments

Comments
 (0)