Skip to content

Commit

Permalink
Tests added, refactored code
Browse files Browse the repository at this point in the history
  • Loading branch information
tauhid621 committed Dec 26, 2023
1 parent 3b990ac commit 4675a2c
Show file tree
Hide file tree
Showing 13 changed files with 2,653 additions and 2,264 deletions.
2 changes: 2 additions & 0 deletions agent/config_endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ func (s *HTTPHandlers) parseEntMetaForConfigEntryKind(kind string, req *http.Req
return s.parseEntMetaNoWildcard(req, entMeta)
}

// ResolvedExportedServices returns all the exported services by resolving wildcards and sameness groups
// in the exported services configuration entry
func (s *HTTPHandlers) ResolvedExportedServices(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
var entMeta acl.EnterpriseMeta
if err := s.parseEntMetaPartition(req, &entMeta); err != nil {
Expand Down
12 changes: 8 additions & 4 deletions agent/config_endpoint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -795,12 +795,16 @@ func TestConfig_Resolved_Exported_Services(t *testing.T) {

expected := []*pbconfigentry.ResolvedExportedService{
{
Service: "api",
ConsumerPeers: []string{"east", "west"},
Service: "api",
Consumers: &pbconfigentry.Consumers{
Peers: []string{"east", "west"},
},
},
{
Service: "db",
ConsumerPeers: []string{"east"},
Service: "db",
Consumers: &pbconfigentry.Consumers{
Peers: []string{"east"},
},
},
}
require.ElementsMatch(t, expected, services)
Expand Down
87 changes: 87 additions & 0 deletions agent/consul/configentry_backend_ce_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1

//go:build !consulent

package consul

import (
"context"
"testing"
"time"

"github.com/stretchr/testify/require"
gogrpc "google.golang.org/grpc"

"github.com/hashicorp/consul/proto/private/pbconfigentry"
"github.com/hashicorp/consul/sdk/freeport"
"github.com/hashicorp/consul/testrpc"
)

func TestConfigEntryBackend_RejectsPartition(t *testing.T) {
if testing.Short() {
t.Skip("too slow for testing.Short")
}

t.Parallel()

_, s1 := testServerWithConfig(t, func(c *Config) {
c.GRPCTLSPort = freeport.GetOne(t)
})
testrpc.WaitForLeader(t, s1.RPC, "dc1")

// make a grpc client to dial s1 directly
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
t.Cleanup(cancel)

conn, err := gogrpc.DialContext(ctx, s1.config.RPCAddr.String(),
gogrpc.WithContextDialer(newServerDialer(s1.config.RPCAddr.String())),
//nolint:staticcheck
gogrpc.WithInsecure(),
gogrpc.WithBlock())
require.NoError(t, err)
t.Cleanup(func() { conn.Close() })

configEntryClient := pbconfigentry.NewConfigEntryServiceClient(conn)

req := pbconfigentry.GetResolvedExportedServicesRequest{
Partition: "test",
}
_, err = configEntryClient.GetResolvedExportedServices(ctx, &req)
require.Error(t, err)
require.Contains(t, err.Error(), "Partitions are a Consul Enterprise feature")
}

func TestConfigEntryBackend_IgnoresDefaultPartition(t *testing.T) {
if testing.Short() {
t.Skip("too slow for testing.Short")
}

t.Parallel()

_, s1 := testServerWithConfig(t, func(c *Config) {
c.GRPCTLSPort = freeport.GetOne(t)
})

testrpc.WaitForLeader(t, s1.RPC, "dc1")

// make a grpc client to dial s1 directly
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
t.Cleanup(cancel)

conn, err := gogrpc.DialContext(ctx, s1.config.RPCAddr.String(),
gogrpc.WithContextDialer(newServerDialer(s1.config.RPCAddr.String())),
//nolint:staticcheck
gogrpc.WithInsecure(),
gogrpc.WithBlock())
require.NoError(t, err)
t.Cleanup(func() { conn.Close() })

configEntryClient := pbconfigentry.NewConfigEntryServiceClient(conn)

req := pbconfigentry.GetResolvedExportedServicesRequest{
Partition: "DeFaUlT",
}
_, err = configEntryClient.GetResolvedExportedServices(ctx, &req)
require.NoError(t, err)
}
9 changes: 2 additions & 7 deletions agent/consul/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ type Server struct {
// operatorBackend is shared between the external and internal gRPC services for peering
operatorBackend *OperatorBackend

// configEntryBackend is shared between the external and internal gRPC services for config entry
// configEntryBackend is shared between the external and internal gRPC services for config entries
configEntryBackend *ConfigEntryBackend

// peerStreamServer is a server used to handle peering streams from external clusters.
Expand Down Expand Up @@ -1039,7 +1039,7 @@ func newGRPCHandlerFromConfig(deps Deps, config *Config, s *Server) connHandler
s.operatorServer = o

s.configEntryBackend = NewConfigEntryBackend(s)
c := configentry.NewServer(configentry.Config{
s.configEntryServer = configentry.NewServer(configentry.Config{
Backend: s.configEntryBackend,
Logger: deps.Logger.Named("grpc-api.configentry"),
ForwardRPC: func(info structs.RPCInfo, fn func(*grpc.ClientConn) error) (bool, error) {
Expand All @@ -1051,7 +1051,6 @@ func newGRPCHandlerFromConfig(deps Deps, config *Config, s *Server) connHandler
},
FSMServer: s,
})
s.configEntryServer = c

register := func(srv *grpc.Server) {
if config.RPCConfig.EnableStreaming {
Expand Down Expand Up @@ -1483,10 +1482,6 @@ func (s *Server) setupExternalGRPC(config *Config, deps Deps, logger hclog.Logge
Datacenter: s.config.Datacenter,
ConnectEnabled: s.config.ConnectEnabled,
ForwardRPC: func(info structs.RPCInfo, fn func(*grpc.ClientConn) error) (bool, error) {
// Only forward the request if the dc in the request matches the server's datacenter.
if info.RequestDatacenter() != "" && info.RequestDatacenter() != config.Datacenter {
return false, fmt.Errorf("requests to generate peering tokens cannot be forwarded to remote datacenters")
}
return s.ForwardGRPC(s.grpcConnPool, info, fn)
},
})
Expand Down
10 changes: 5 additions & 5 deletions agent/consul/state/config_entry_exported_services.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,16 +67,16 @@ func getExportedServicesConfigEntryTxn(
return idx, export, nil
}

// ExportedServices returns the list of exported services along with consumers.
// Sameness Groups and wild card entries are expanded.
func (s *Store) ExportedServices(ws memdb.WatchSet, entMeta *acl.EnterpriseMeta) (uint64, []*pbconfigentry.ResolvedExportedService, error) {
// ResolvedExportedServices returns the list of exported services along with consumers.
// Sameness Groups and wild card entries are resolved.
func (s *Store) ResolvedExportedServices(ws memdb.WatchSet, entMeta *acl.EnterpriseMeta) (uint64, []*pbconfigentry.ResolvedExportedService, error) {
tx := s.db.ReadTxn()
defer tx.Abort()

return exportedServicesTxn(tx, ws, entMeta)
return resolvedExportedServicesTxn(tx, ws, entMeta)
}

func exportedServicesTxn(tx ReadTxn, ws memdb.WatchSet, entMeta *acl.EnterpriseMeta) (uint64, []*pbconfigentry.ResolvedExportedService, error) {
func resolvedExportedServicesTxn(tx ReadTxn, ws memdb.WatchSet, entMeta *acl.EnterpriseMeta) (uint64, []*pbconfigentry.ResolvedExportedService, error) {
var resp []*pbconfigentry.ResolvedExportedService

// getSimplifiedExportedServices resolves the sameness group information to partitions and peers.
Expand Down
6 changes: 4 additions & 2 deletions agent/consul/state/config_entry_exported_services_ce.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,10 @@ func prepareExportedServicesResponse(exportedServices map[structs.ServiceName]ma
sort.Strings(consumerPeers)

resp = append(resp, &pbconfigentry.ResolvedExportedService{
Service: svc.Name,
ConsumerPeers: consumerPeers,
Service: svc.Name,
Consumers: &pbconfigentry.Consumers{
Peers: consumerPeers,
},
})
}

Expand Down
50 changes: 50 additions & 0 deletions agent/consul/state/config_entry_exported_services_ce_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1

//go:build !consulent

package state

import (
"testing"

"github.com/hashicorp/consul/agent/structs"
"github.com/hashicorp/consul/proto/private/pbconfigentry"
"github.com/stretchr/testify/require"
)

func TestStore_prepareExportedServicesResponse(t *testing.T) {
var exportedServices = make(map[structs.ServiceName]map[structs.ServiceConsumer]struct{})

svc1 := structs.NewServiceName("db", nil)
exportedServices[svc1] = make(map[structs.ServiceConsumer]struct{})
exportedServices[svc1][structs.ServiceConsumer{Peer: "west"}] = struct{}{}
exportedServices[svc1][structs.ServiceConsumer{Peer: "east"}] = struct{}{}

// Adding partition to ensure that it's not included in response
exportedServices[svc1][structs.ServiceConsumer{Partition: "east"}] = struct{}{}

svc2 := structs.NewServiceName("web", nil)
exportedServices[svc2] = make(map[structs.ServiceConsumer]struct{})
exportedServices[svc2][structs.ServiceConsumer{Peer: "peer-a"}] = struct{}{}
exportedServices[svc2][structs.ServiceConsumer{Peer: "peer-b"}] = struct{}{}

resp := prepareExportedServicesResponse(exportedServices)

expected := []*pbconfigentry.ResolvedExportedService{
{
Service: "db",
Consumers: &pbconfigentry.Consumers{
Peers: []string{"east", "west"},
},
},
{
Service: "web",
Consumers: &pbconfigentry.Consumers{
Peers: []string{"peer-a", "peer-b"},
},
},
}

require.ElementsMatch(t, expected, resp)
}
Loading

0 comments on commit 4675a2c

Please sign in to comment.