Skip to content

Commit 09cf89e

Browse files
committed
cli/compose/convert: convertEndpointSpec: fix sorting of ports
The existing code only sorted by PublishedPort (host port), and did not account for multiple ports mapped to the same host-port, but using a different protocol. Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
1 parent db28780 commit 09cf89e

File tree

1 file changed

+27
-6
lines changed

1 file changed

+27
-6
lines changed

cli/compose/convert/service.go

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -572,21 +572,42 @@ func convertResources(source composetypes.Resources) (*swarm.ResourceRequirement
572572
return resources, nil
573573
}
574574

575+
// compareSwarmPortConfig returns the lexical ordering of a and b, and can be used
576+
// with [slices.SortFunc].
577+
//
578+
// The comparison is performed in the following priority order:
579+
//
580+
// 1. PublishedPort (host port)
581+
// 2. TargetPort (container port)
582+
// 3. Protocol
583+
// 4. PublishMode
584+
//
585+
// TODO(thaJeztah): define this on swarm.PortConfig itself to allow re-use.
586+
func compareSwarmPortConfig(a, b swarm.PortConfig) int {
587+
if n := cmp.Compare(a.PublishedPort, b.PublishedPort); n != 0 {
588+
return n
589+
}
590+
if n := cmp.Compare(a.TargetPort, b.TargetPort); n != 0 {
591+
return n
592+
}
593+
if n := cmp.Compare(a.Protocol, b.Protocol); n != 0 {
594+
return n
595+
}
596+
return cmp.Compare(a.PublishMode, b.PublishMode)
597+
}
598+
575599
func convertEndpointSpec(endpointMode string, source []composetypes.ServicePortConfig) *swarm.EndpointSpec {
576600
portConfigs := make([]swarm.PortConfig, 0, len(source))
577601
for _, port := range source {
578-
portConfig := swarm.PortConfig{
602+
portConfigs = append(portConfigs, swarm.PortConfig{
579603
Protocol: network.IPProtocol(port.Protocol),
580604
TargetPort: port.Target,
581605
PublishedPort: port.Published,
582606
PublishMode: swarm.PortConfigPublishMode(port.Mode),
583-
}
584-
portConfigs = append(portConfigs, portConfig)
607+
})
585608
}
586609

587-
sort.Slice(portConfigs, func(i, j int) bool {
588-
return portConfigs[i].PublishedPort < portConfigs[j].PublishedPort
589-
})
610+
slices.SortFunc(portConfigs, compareSwarmPortConfig)
590611

591612
return &swarm.EndpointSpec{
592613
Mode: swarm.ResolutionMode(strings.ToLower(endpointMode)),

0 commit comments

Comments
 (0)