Merge pull request #47336 from xiangpengzhao/fix-dup-port

Automatic merge from submit-queue

Validate if service has duplicate port

**What this PR does / why we need it**:
Validate if a service has duplicate Spec.Ports.Port (same number with same protocol)

xref #47221 
fixes this part: 
>It is possible to express a Service with multiple ports blocks with the same number. This is not very useful and may cause trouble for implementations of Services.

**Special notes for your reviewer**:
/cc @thockin @liggitt @mengqiy 
@kubernetes/sig-network-pr-reviews

**Release note**:

```release-note
NONE
```
This commit is contained in:
Kubernetes Submit Queue 2017-08-01 14:31:02 -07:00 committed by GitHub
commit 7be37ef6ab
2 changed files with 31 additions and 0 deletions

View File

@ -2913,6 +2913,19 @@ func ValidateService(service *api.Service) field.ErrorList {
nodePorts[key] = true
}
// Check for duplicate Ports, considering (protocol,port) pairs
portsPath = specPath.Child("ports")
ports := make(map[api.ServicePort]bool)
for i, port := range service.Spec.Ports {
portPath := portsPath.Index(i)
key := api.ServicePort{Protocol: port.Protocol, Port: port.Port}
_, found := ports[key]
if found {
allErrs = append(allErrs, field.Duplicate(portPath, key))
}
ports[key] = true
}
// Check for duplicate TargetPort
portsPath = specPath.Child("ports")
targetPorts := make(map[api.ServicePort]bool)

View File

@ -6302,6 +6302,24 @@ func TestValidateService(t *testing.T) {
},
numErrs: 0,
},
{
name: "invalid duplicate ports (with same protocol)",
tweakSvc: func(s *api.Service) {
s.Spec.Type = api.ServiceTypeClusterIP
s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(8080)})
s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "r", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(80)})
},
numErrs: 1,
},
{
name: "valid duplicate ports (with different protocols)",
tweakSvc: func(s *api.Service) {
s.Spec.Type = api.ServiceTypeClusterIP
s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(8080)})
s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "r", Port: 12345, Protocol: "UDP", TargetPort: intstr.FromInt(80)})
},
numErrs: 0,
},
{
name: "invalid duplicate targetports (number with same protocol)",
tweakSvc: func(s *api.Service) {