Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

check that a container_name is used only once across all services declarations #585

Merged
merged 1 commit into from
Feb 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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{}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could use utils.Set, which offers Has method

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't keep the original service name with a Set only the container_name value

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`)
}