Skip to content

Commit

Permalink
fix: port names of the headless service are conflict (apecloud#8400)
Browse files Browse the repository at this point in the history
  • Loading branch information
leon-inf authored Nov 5, 2024
1 parent 3837f3b commit 5fdffaf
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
7 changes: 4 additions & 3 deletions pkg/controller/instanceset/object_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (

corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/sets"

workloads "github.com/apecloud/kubeblocks/apis/workloads/v1"
"github.com/apecloud/kubeblocks/pkg/constant"
Expand Down Expand Up @@ -58,19 +59,19 @@ func buildHeadlessSvc(its workloads.InstanceSet, labels, selectors map[string]st
AddAnnotationsInMap(annotations).
SetPublishNotReadyAddresses(true)

portNames := sets.New[string]()
for _, container := range its.Spec.Template.Spec.Containers {
for _, port := range container.Ports {
servicePort := corev1.ServicePort{
Protocol: port.Protocol,
Port: port.ContainerPort,
}
switch {
case len(port.Name) > 0:
case len(port.Name) > 0 && !portNames.Has(port.Name):
portNames.Insert(port.Name)
servicePort.Name = port.Name
servicePort.TargetPort = intstr.FromString(port.Name)
default:
servicePort.Name = fmt.Sprintf("%s-%d", strings.ToLower(string(port.Protocol)), port.ContainerPort)
servicePort.TargetPort = intstr.FromInt(int(port.ContainerPort))
}
hdlBuilder.AddPorts(servicePort)
}
Expand Down
24 changes: 22 additions & 2 deletions pkg/controller/instanceset/object_builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,10 +155,30 @@ var _ = Describe("object generation transformer test.", func() {
})
})

Context("getHeadlessSvcName function", func() {
It("should work well", func() {
Context("headless service", func() {
It("getHeadlessSvcName", func() {
Expect(getHeadlessSvcName(its.Name)).Should(Equal("bar-headless"))
})

It("buildHeadlessSvc - duplicate port names", func() {
port := its.Spec.Template.Spec.Containers[0].Ports[0]
its.Spec.Template.Spec.Containers = append(its.Spec.Template.Spec.Containers, corev1.Container{
Name: "duplicate-port-name",
Image: "image",
Ports: []corev1.ContainerPort{
{
Name: port.Name,
Protocol: port.Protocol,
ContainerPort: port.ContainerPort + 1,
},
},
})
svc := buildHeadlessSvc(*its, nil, nil)
Expect(svc).ShouldNot(BeNil())
Expect(len(svc.Spec.Ports)).Should(Equal(2))
Expect(svc.Spec.Ports[0].Name).Should(Equal(port.Name))
Expect(svc.Spec.Ports[1].Name).ShouldNot(Equal(port.Name))
})
})

Context("findSvcPort function", func() {
Expand Down

0 comments on commit 5fdffaf

Please sign in to comment.