Skip to content

Commit

Permalink
catalog: Default protocol to tcp in catalog.Service if unspecified (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
ishustava authored Sep 15, 2023
1 parent 5cde50d commit a89938e
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
25 changes: 25 additions & 0 deletions internal/catalog/internal/types/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,34 @@ func RegisterService(r resource.Registry) {
Proto: &pbcatalog.Service{},
Scope: resource.ScopeNamespace,
Validate: ValidateService,
Mutate: MutateService,
})
}

func MutateService(res *pbresource.Resource) error {
var service pbcatalog.Service

if err := res.Data.UnmarshalTo(&service); err != nil {
return err
}

changed := false

// Default service port protocols.
for _, port := range service.Ports {
if port.Protocol == pbcatalog.Protocol_PROTOCOL_UNSPECIFIED {
port.Protocol = pbcatalog.Protocol_PROTOCOL_TCP
changed = true
}
}

if !changed {
return nil
}

return res.Data.MarshalFrom(&service)
}

func ValidateService(res *pbresource.Resource) error {
var service pbcatalog.Service

Expand Down
33 changes: 33 additions & 0 deletions internal/catalog/internal/types/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"google.golang.org/protobuf/types/known/anypb"

"github.com/hashicorp/consul/internal/resource"
"github.com/hashicorp/consul/internal/resource/resourcetest"
pbcatalog "github.com/hashicorp/consul/proto-public/pbcatalog/v1alpha1"
"github.com/hashicorp/consul/proto-public/pbresource"
)
Expand All @@ -34,6 +35,38 @@ func createServiceResource(t *testing.T, data protoreflect.ProtoMessage) *pbreso
return res
}

func TestMutateServicePorts(t *testing.T) {
data := &pbcatalog.Service{
Workloads: &pbcatalog.WorkloadSelector{
Names: []string{"foo", "bar"},
},
Ports: []*pbcatalog.ServicePort{
{
TargetPort: "tcp",
Protocol: pbcatalog.Protocol_PROTOCOL_UNSPECIFIED,
},
{
TargetPort: "http",
Protocol: pbcatalog.Protocol_PROTOCOL_HTTP,
},
},
VirtualIps: []string{"198.18.0.1"},
}

res := createServiceResource(t, data)

err := MutateService(res)
require.NoError(t, err)

got := resourcetest.MustDecode[*pbcatalog.Service](t, res)

require.Len(t, got.Data.Ports, 2)
require.Equal(t, pbcatalog.Protocol_PROTOCOL_TCP, got.Data.Ports[0].Protocol)

// Check that specified protocol is not mutated.
require.Equal(t, data.Ports[1].Protocol, got.Data.Ports[1].Protocol)
}

func TestValidateService_Ok(t *testing.T) {
data := &pbcatalog.Service{
Workloads: &pbcatalog.WorkloadSelector{
Expand Down

0 comments on commit a89938e

Please sign in to comment.