From 3f28074c545eca1b14537b6e534126f30c3e89ec Mon Sep 17 00:00:00 2001 From: xiangpengzhao Date: Mon, 12 Jun 2017 14:31:37 +0800 Subject: [PATCH] Validate if service has duplicate port --- pkg/api/validation/validation.go | 13 +++++++++++++ pkg/api/validation/validation_test.go | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/pkg/api/validation/validation.go b/pkg/api/validation/validation.go index f6bd510bfdd..a6b49774425 100644 --- a/pkg/api/validation/validation.go +++ b/pkg/api/validation/validation.go @@ -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) diff --git a/pkg/api/validation/validation_test.go b/pkg/api/validation/validation_test.go index 6f0940d03e1..1877140cfaf 100644 --- a/pkg/api/validation/validation_test.go +++ b/pkg/api/validation/validation_test.go @@ -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) {