Skip to content

Commit 8098098

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 038c5f3 commit 8098098

1 file changed

Lines changed: 27 additions & 6 deletions

File tree

cli/compose/convert/service.go

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

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

584-
sort.Slice(portConfigs, func(i, j int) bool {
585-
return portConfigs[i].PublishedPort < portConfigs[j].PublishedPort
586-
})
607+
slices.SortFunc(portConfigs, compareSwarmPortConfig)
587608

588609
return &swarm.EndpointSpec{
589610
Mode: swarm.ResolutionMode(strings.ToLower(endpointMode)),

0 commit comments

Comments
 (0)