From 506ea1a2064dc0c12f8678e84d76f19332930762 Mon Sep 17 00:00:00 2001 From: Diptanu Choudhury Date: Mon, 2 May 2016 13:40:49 -0700 Subject: [PATCH] Ensuring service names are unique --- nomad/structs/structs.go | 8 +++++++- nomad/structs/structs_test.go | 12 ++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/nomad/structs/structs.go b/nomad/structs/structs.go index f461c9b05..d06eafbc6 100644 --- a/nomad/structs/structs.go +++ b/nomad/structs/structs.go @@ -1772,13 +1772,19 @@ func (t *Task) Validate() error { func validateServices(t *Task) error { var mErr multierror.Error - // Ensure that services don't ask for non-existent ports. + // Ensure that services don't ask for non-existent ports and their names are + // unique. servicePorts := make(map[string][]string) + knownServices := make(map[string]struct{}) for i, service := range t.Services { if err := service.Validate(); err != nil { outer := fmt.Errorf("service %d validation failed: %s", i, err) mErr.Errors = append(mErr.Errors, outer) } + if _, ok := knownServices[service.Name]; ok { + mErr.Errors = append(mErr.Errors, fmt.Errorf("service %q is duplicate", service.Name)) + } + knownServices[service.Name] = struct{}{} if service.PortLabel != "" { servicePorts[service.PortLabel] = append(servicePorts[service.PortLabel], service.Name) diff --git a/nomad/structs/structs_test.go b/nomad/structs/structs_test.go index fbf3ffd5b..84e136ad7 100644 --- a/nomad/structs/structs_test.go +++ b/nomad/structs/structs_test.go @@ -276,7 +276,7 @@ func TestTask_Validate(t *testing.T) { } func TestTask_Validate_Services(t *testing.T) { - s := &Service{ + s1 := &Service{ Name: "service-name", PortLabel: "bar", Checks: []*ServiceCheck{ @@ -287,6 +287,10 @@ func TestTask_Validate_Services(t *testing.T) { }, } + s2 := &Service{ + Name: "service-name", + } + task := &Task{ Name: "web", Driver: "docker", @@ -296,7 +300,7 @@ func TestTask_Validate_Services(t *testing.T) { MemoryMB: 100, IOPS: 10, }, - Services: []*Service{s}, + Services: []*Service{s1, s2}, } err := task.Validate() if err == nil { @@ -305,6 +309,10 @@ func TestTask_Validate_Services(t *testing.T) { if !strings.Contains(err.Error(), "referenced by services service-name does not exist") { t.Fatalf("err: %s", err) } + + if !strings.Contains(err.Error(), "service \"service-name\" is duplicate") { + t.Fatalf("err: %v", err) + } } func TestTask_Validate_LogConfig(t *testing.T) {