catalog: Default protocol to tcp in catalog.Service if unspecified (#18832)

This commit is contained in:
Iryna Shustava 2023-09-15 15:11:56 -06:00 committed by GitHub
parent 5cde50dee7
commit a89938e0c1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 58 additions and 0 deletions

View File

@ -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

View File

@ -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"
)
@ -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{