Skip to content

Commit

Permalink
check that a container_name is used only once across all services dec…
Browse files Browse the repository at this point in the history
…larations

Signed-off-by: Guillaume Lours <[email protected]>
  • Loading branch information
glours authored and ndeloof committed Feb 20, 2024
1 parent 4c12ed6 commit 5d934a2
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
8 changes: 8 additions & 0 deletions loader/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import (

// checkConsistency validate a compose model is consistent
func checkConsistency(project *types.Project) error {
containerNames := map[string]string{}
for _, s := range project.Services {
if s.Build == nil && s.Image == "" {
return fmt.Errorf("service %q has neither an image nor a build context specified: %w", s.Name, errdefs.ErrInvalid)
Expand Down Expand Up @@ -123,6 +124,13 @@ func checkConsistency(project *types.Project) error {
s.Deploy.Replicas = s.Scale
}

if s.ContainerName != "" {
if existing, ok := containerNames[s.ContainerName]; ok {
return fmt.Errorf(`"services.%s": container name "%s" is already in use by "services.%s": %w`, s.Name, s.ContainerName, existing, errdefs.ErrInvalid)
}
containerNames[s.ContainerName] = s.Name
}

if s.GetScale() > 1 && s.ContainerName != "" {
attr := "scale"
if s.Scale == nil {
Expand Down
19 changes: 19 additions & 0 deletions loader/validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -259,3 +259,22 @@ func TestValidateDependsOn(t *testing.T) {
err := checkConsistency(&project)
assert.Error(t, err, `service "myservice" depends on undefined service missingservice: invalid compose project`)
}

func TestValidateContainerName(t *testing.T) {
project := types.Project{
Services: types.Services{
"myservice": {
Name: "myservice",
Image: "scratch",
ContainerName: "mycontainer",
},
"myservice2": {
Name: "myservice2",
Image: "scratch",
ContainerName: "mycontainer",
},
},
}
err := checkConsistency(&project)
assert.Error(t, err, `"services.myservice2": container name "mycontainer" is already in use by "services.myservice": invalid compose project`)
}

0 comments on commit 5d934a2

Please sign in to comment.