Update e2e tests for namespaces (#16627)

* Refactored "NewGatewayService" to handle namespaces, fixed
TestHTTPRouteFlattening test

* Fixed existing http_route tests for namespacing

* Squash aclEnterpriseMeta for ResourceRefs and HTTPServices, accept
namespace for creating connect services and regular services

* Use require instead of assert after creating namespaces in
http_route_tests

* Refactor NewConnectService and NewGatewayService functions to use cfg
objects to reduce number of method args

* Rename field on SidecarConfig in tests from `SidecarServiceName` to
`Name` to avoid stutter
This commit is contained in:
John Maguire 2023-03-15 13:51:36 -04:00 committed by GitHub
parent 48f0a2837b
commit ff5887a99e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 179 additions and 83 deletions

View File

@ -4,8 +4,9 @@ import (
"fmt" "fmt"
"strings" "strings"
"github.com/hashicorp/consul/acl"
"github.com/miekg/dns" "github.com/miekg/dns"
"github.com/hashicorp/consul/acl"
) )
// BoundRoute indicates a route that has parent gateways which // BoundRoute indicates a route that has parent gateways which

View File

@ -142,18 +142,24 @@ func (g ConnectContainer) GetStatus() (string, error) {
return state.Status, err return state.Status, err
} }
type SidecarConfig struct {
Name string
ServiceID string
Namespace string
}
// NewConnectService returns a container that runs envoy sidecar, launched by // NewConnectService returns a container that runs envoy sidecar, launched by
// "consul connect envoy", for service name (serviceName) on the specified // "consul connect envoy", for service name (serviceName) on the specified
// node. The container exposes port serviceBindPort and envoy admin port // node. The container exposes port serviceBindPort and envoy admin port
// (19000) by mapping them onto host ports. The container's name has a prefix // (19000) by mapping them onto host ports. The container's name has a prefix
// combining datacenter and name. // combining datacenter and name.
func NewConnectService(ctx context.Context, sidecarServiceName string, serviceID string, serviceBindPorts []int, node cluster.Agent) (*ConnectContainer, error) { func NewConnectService(ctx context.Context, sidecarCfg SidecarConfig, serviceBindPorts []int, node cluster.Agent) (*ConnectContainer, error) {
nodeConfig := node.GetConfig() nodeConfig := node.GetConfig()
if nodeConfig.ScratchDir == "" { if nodeConfig.ScratchDir == "" {
return nil, fmt.Errorf("node ScratchDir is required") return nil, fmt.Errorf("node ScratchDir is required")
} }
namePrefix := fmt.Sprintf("%s-service-connect-%s", node.GetDatacenter(), sidecarServiceName) namePrefix := fmt.Sprintf("%s-service-connect-%s", node.GetDatacenter(), sidecarCfg.Name)
containerName := utils.RandName(namePrefix) containerName := utils.RandName(namePrefix)
envoyVersion := getEnvoyVersion() envoyVersion := getEnvoyVersion()
@ -181,8 +187,9 @@ func NewConnectService(ctx context.Context, sidecarServiceName string, serviceID
Name: containerName, Name: containerName,
Cmd: []string{ Cmd: []string{
"consul", "connect", "envoy", "consul", "connect", "envoy",
"-sidecar-for", serviceID, "-sidecar-for", sidecarCfg.ServiceID,
"-admin-bind", fmt.Sprintf("0.0.0.0:%d", internalAdminPort), "-admin-bind", fmt.Sprintf("0.0.0.0:%d", internalAdminPort),
"-namespace", sidecarCfg.Namespace,
"--", "--",
"--log-level", envoyLogLevel, "--log-level", envoyLogLevel,
}, },
@ -240,7 +247,7 @@ func NewConnectService(ctx context.Context, sidecarServiceName string, serviceID
ip: info.IP, ip: info.IP,
externalAdminPort: info.MappedPorts[adminPortStr].Int(), externalAdminPort: info.MappedPorts[adminPortStr].Int(),
internalAdminPort: internalAdminPort, internalAdminPort: internalAdminPort,
serviceName: sidecarServiceName, serviceName: sidecarCfg.Name,
} }
for _, port := range appPortStrs { for _, port := range appPortStrs {
@ -248,9 +255,9 @@ func NewConnectService(ctx context.Context, sidecarServiceName string, serviceID
} }
fmt.Printf("NewConnectService: name %s, mapped App Port %d, service bind port %v\n", fmt.Printf("NewConnectService: name %s, mapped App Port %d, service bind port %v\n",
serviceID, out.appPort, serviceBindPorts) sidecarCfg.ServiceID, out.appPort, serviceBindPorts)
fmt.Printf("NewConnectService sidecar: name %s, mapped admin port %d, admin port %d\n", fmt.Printf("NewConnectService sidecar: name %s, mapped admin port %d, admin port %d\n",
sidecarServiceName, out.externalAdminPort, internalAdminPort) sidecarCfg.Name, out.externalAdminPort, internalAdminPort)
return out, nil return out, nil
} }

View File

@ -112,7 +112,6 @@ func (g gatewayContainer) GetPort(port int) (int, error) {
return 0, fmt.Errorf("port does not exist") return 0, fmt.Errorf("port does not exist")
} }
return p, nil return p, nil
} }
func (g gatewayContainer) Restart() error { func (g gatewayContainer) Restart() error {
@ -140,13 +139,19 @@ func (g gatewayContainer) GetStatus() (string, error) {
return state.Status, err return state.Status, err
} }
func NewGatewayService(ctx context.Context, name string, kind string, node libcluster.Agent, ports ...int) (Service, error) { type GatewayConfig struct {
Name string
Kind string
Namespace string
}
func NewGatewayService(ctx context.Context, gwCfg GatewayConfig, node libcluster.Agent, ports ...int) (Service, error) {
nodeConfig := node.GetConfig() nodeConfig := node.GetConfig()
if nodeConfig.ScratchDir == "" { if nodeConfig.ScratchDir == "" {
return nil, fmt.Errorf("node ScratchDir is required") return nil, fmt.Errorf("node ScratchDir is required")
} }
namePrefix := fmt.Sprintf("%s-service-gateway-%s", node.GetDatacenter(), name) namePrefix := fmt.Sprintf("%s-service-gateway-%s", node.GetDatacenter(), gwCfg.Name)
containerName := utils.RandName(namePrefix) containerName := utils.RandName(namePrefix)
envoyVersion := getEnvoyVersion() envoyVersion := getEnvoyVersion()
@ -174,9 +179,10 @@ func NewGatewayService(ctx context.Context, name string, kind string, node libcl
Name: containerName, Name: containerName,
Cmd: []string{ Cmd: []string{
"consul", "connect", "envoy", "consul", "connect", "envoy",
fmt.Sprintf("-gateway=%s", kind), fmt.Sprintf("-gateway=%s", gwCfg.Kind),
"-register", "-register",
"-service", name, "-namespace", gwCfg.Namespace,
"-service", gwCfg.Name,
"-address", "{{ GetInterfaceIP \"eth0\" }}:8443", "-address", "{{ GetInterfaceIP \"eth0\" }}:8443",
"-admin-bind", fmt.Sprintf("0.0.0.0:%d", adminPort), "-admin-bind", fmt.Sprintf("0.0.0.0:%d", adminPort),
"--", "--",
@ -242,7 +248,7 @@ func NewGatewayService(ctx context.Context, name string, kind string, node libcl
ip: info.IP, ip: info.IP,
port: info.MappedPorts[portStr].Int(), port: info.MappedPorts[portStr].Int(),
adminPort: info.MappedPorts[adminPortStr].Int(), adminPort: info.MappedPorts[adminPortStr].Int(),
serviceName: name, serviceName: gwCfg.Name,
portMappings: portMappings, portMappings: portMappings,
} }

View File

@ -5,10 +5,11 @@ import (
"fmt" "fmt"
"testing" "testing"
"github.com/stretchr/testify/require"
"github.com/hashicorp/consul/api" "github.com/hashicorp/consul/api"
libcluster "github.com/hashicorp/consul/test/integration/consul-container/libs/cluster" libcluster "github.com/hashicorp/consul/test/integration/consul-container/libs/cluster"
"github.com/hashicorp/consul/test/integration/consul-container/libs/utils" "github.com/hashicorp/consul/test/integration/consul-container/libs/utils"
"github.com/stretchr/testify/require"
) )
const ( const (
@ -27,13 +28,14 @@ type SidecarService struct {
} }
type ServiceOpts struct { type ServiceOpts struct {
Name string Name string
ID string ID string
Meta map[string]string Meta map[string]string
HTTPPort int HTTPPort int
GRPCPort int GRPCPort int
Checks Checks Checks Checks
Connect SidecarService Connect SidecarService
Namespace string
} }
// createAndRegisterStaticServerAndSidecar register the services and launch static-server containers // createAndRegisterStaticServerAndSidecar register the services and launch static-server containers
@ -55,8 +57,12 @@ func createAndRegisterStaticServerAndSidecar(node libcluster.Agent, grpcPort int
deferClean.Add(func() { deferClean.Add(func() {
_ = serverService.Terminate() _ = serverService.Terminate()
}) })
sidecarCfg := SidecarConfig{
serverConnectProxy, err := NewConnectService(context.Background(), fmt.Sprintf("%s-sidecar", svc.ID), svc.ID, []int{svc.Port}, node) // bindPort not used Name: fmt.Sprintf("%s-sidecar", svc.ID),
ServiceID: svc.ID,
Namespace: svc.Namespace,
}
serverConnectProxy, err := NewConnectService(context.Background(), sidecarCfg, []int{svc.Port}, node) // bindPort not used
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
@ -82,6 +88,7 @@ func CreateAndRegisterStaticServerAndSidecar(node libcluster.Agent, serviceOpts
Proxy: &api.AgentServiceConnectProxyConfig{}, Proxy: &api.AgentServiceConnectProxyConfig{},
}, },
}, },
Namespace: serviceOpts.Namespace,
Check: &api.AgentServiceCheck{ Check: &api.AgentServiceCheck{
Name: "Static Server Listening", Name: "Static Server Listening",
TCP: fmt.Sprintf("127.0.0.1:%d", serviceOpts.HTTPPort), TCP: fmt.Sprintf("127.0.0.1:%d", serviceOpts.HTTPPort),
@ -160,7 +167,12 @@ func CreateAndRegisterStaticClientSidecar(
} }
// Create a service and proxy instance // Create a service and proxy instance
clientConnectProxy, err := NewConnectService(context.Background(), fmt.Sprintf("%s-sidecar", StaticClientServiceName), StaticClientServiceName, []int{libcluster.ServiceUpstreamLocalBindPort}, node) sidecarCfg := SidecarConfig{
Name: fmt.Sprintf("%s-sidecar", StaticClientServiceName),
ServiceID: StaticClientServiceName,
}
clientConnectProxy, err := NewConnectService(context.Background(), sidecarCfg, []int{libcluster.ServiceUpstreamLocalBindPort}, node)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -67,9 +67,13 @@ func BasicPeeringTwoClustersSetup(
}) })
// Create the mesh gateway for dataplane traffic and peering control plane traffic (if enabled) // Create the mesh gateway for dataplane traffic and peering control plane traffic (if enabled)
acceptingClusterGateway, err := libservice.NewGatewayService(context.Background(), "mesh", "mesh", acceptingCluster.Clients()[0]) gwCfg := libservice.GatewayConfig{
Name: "mesh",
Kind: "mesh",
}
acceptingClusterGateway, err := libservice.NewGatewayService(context.Background(), gwCfg, acceptingCluster.Clients()[0])
require.NoError(t, err) require.NoError(t, err)
dialingClusterGateway, err := libservice.NewGatewayService(context.Background(), "mesh", "mesh", dialingCluster.Clients()[0]) dialingClusterGateway, err := libservice.NewGatewayService(context.Background(), gwCfg, dialingCluster.Clients()[0])
require.NoError(t, err) require.NoError(t, err)
// Enable peering control plane traffic through mesh gateway // Enable peering control plane traffic through mesh gateway

View File

@ -9,6 +9,9 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/hashicorp/consul/api" "github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/sdk/testutil/retry" "github.com/hashicorp/consul/sdk/testutil/retry"
libassert "github.com/hashicorp/consul/test/integration/consul-container/libs/assert" libassert "github.com/hashicorp/consul/test/integration/consul-container/libs/assert"
@ -17,8 +20,6 @@ import (
libtopology "github.com/hashicorp/consul/test/integration/consul-container/libs/topology" libtopology "github.com/hashicorp/consul/test/integration/consul-container/libs/topology"
"github.com/hashicorp/consul/test/integration/consul-container/libs/utils" "github.com/hashicorp/consul/test/integration/consul-container/libs/utils"
"github.com/hashicorp/go-cleanhttp" "github.com/hashicorp/go-cleanhttp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
// Creates a gateway service and tests to see if it is routable // Creates a gateway service and tests to see if it is routable
@ -145,7 +146,7 @@ func createCluster(t *testing.T, ports ...int) *libcluster.Cluster {
return cluster return cluster
} }
func createGateway(gatewayName string, protocol string, listenerPort int) *api.APIGatewayConfigEntry { func createGatewayConfigEntry(gatewayName, protocol, namespace string, listenerPort int) *api.APIGatewayConfigEntry {
return &api.APIGatewayConfigEntry{ return &api.APIGatewayConfigEntry{
Kind: api.APIGateway, Kind: api.APIGateway,
Name: gatewayName, Name: gatewayName,
@ -156,6 +157,7 @@ func createGateway(gatewayName string, protocol string, listenerPort int) *api.A
Protocol: protocol, Protocol: protocol,
}, },
}, },
Namespace: namespace,
} }
} }
@ -208,8 +210,8 @@ func createService(t *testing.T, cluster *libcluster.Cluster, serviceOpts *libse
libassert.CatalogServiceExists(t, client, serviceOpts.Name, nil) libassert.CatalogServiceExists(t, client, serviceOpts.Name, nil)
return service return service
} }
func createServices(t *testing.T, cluster *libcluster.Cluster, ports ...int) (libservice.Service, libservice.Service) { func createServices(t *testing.T, cluster *libcluster.Cluster, ports ...int) (libservice.Service, libservice.Service) {
node := cluster.Agents[0] node := cluster.Agents[0]
client := node.GetClient() client := node.GetClient()
@ -222,8 +224,12 @@ func createServices(t *testing.T, cluster *libcluster.Cluster, ports ...int) (li
} }
clientConnectProxy := createService(t, cluster, serviceOpts, nil) clientConnectProxy := createService(t, cluster, serviceOpts, nil)
gwCfg := libservice.GatewayConfig{
Name: "api-gateway",
Kind: "api",
}
gatewayService, err := libservice.NewGatewayService(context.Background(), "api-gateway", "api", cluster.Agents[0], ports...) gatewayService, err := libservice.NewGatewayService(context.Background(), gwCfg, cluster.Agents[0], ports...)
require.NoError(t, err) require.NoError(t, err)
libassert.CatalogServiceExists(t, client, "api-gateway", nil) libassert.CatalogServiceExists(t, client, "api-gateway", nil)
@ -284,7 +290,7 @@ func checkRoute(t *testing.T, port int, path string, headers map[string]string,
r.Fatal("unexpected response code returned") r.Fatal("unexpected response code returned")
} }
//if debug is expected, debug should be in the response body // if debug is expected, debug should be in the response body
assert.Equal(t, expected.debug, strings.Contains(string(body), "debug")) assert.Equal(t, expected.debug, strings.Contains(string(body), "debug"))
if expected.statusCode != res.StatusCode { if expected.statusCode != res.StatusCode {
r.Fatal("unexpected response body returned") r.Fatal("unexpected response body returned")
@ -293,7 +299,6 @@ func checkRoute(t *testing.T, port int, path string, headers map[string]string,
if !strings.Contains(string(body), phrase) { if !strings.Contains(string(body), phrase) {
r.Fatal("received an incorrect response ", string(body)) r.Fatal("received an incorrect response ", string(body))
} }
}) })
} }

View File

@ -57,28 +57,36 @@ func TestHTTPRouteFlattening(t *testing.T) {
cluster, _, _ := libtopology.NewCluster(t, clusterConfig) cluster, _, _ := libtopology.NewCluster(t, clusterConfig)
client := cluster.Agents[0].GetClient() client := cluster.Agents[0].GetClient()
namespace := getNamespace()
if namespace != "" {
ns := &api.Namespace{Name: namespace}
_, _, err := client.Namespaces().Create(ns, nil)
require.NoError(t, err)
}
service1ResponseCode := 200 service1ResponseCode := 200
service2ResponseCode := 418 service2ResponseCode := 418
serviceOne := createService(t, cluster, &libservice.ServiceOpts{ serviceOne := createService(t, cluster, &libservice.ServiceOpts{
Name: "service1", Name: "service1",
ID: "service1", ID: "service1",
HTTPPort: 8080, HTTPPort: 8080,
GRPCPort: 8079, GRPCPort: 8079,
Namespace: namespace,
}, []string{ }, []string{
// customizes response code so we can distinguish between which service is responding // customizes response code so we can distinguish between which service is responding
"-echo-server-default-params", fmt.Sprintf("status=%d", service1ResponseCode), "-echo-server-default-params", fmt.Sprintf("status=%d", service1ResponseCode),
}) })
serviceTwo := createService(t, cluster, &libservice.ServiceOpts{ serviceTwo := createService(t, cluster, &libservice.ServiceOpts{
Name: "service2", Name: "service2",
ID: "service2", ID: "service2",
HTTPPort: 8081, HTTPPort: 8081,
GRPCPort: 8082, GRPCPort: 8082,
Namespace: namespace,
}, []string{ }, []string{
"-echo-server-default-params", fmt.Sprintf("status=%d", service2ResponseCode), "-echo-server-default-params", fmt.Sprintf("status=%d", service2ResponseCode),
}, },
) )
namespace := getNamespace()
gatewayName := randomName("gw", 16) gatewayName := randomName("gw", 16)
routeOneName := randomName("route", 16) routeOneName := randomName("route", 16)
routeTwoName := randomName("route", 16) routeTwoName := randomName("route", 16)
@ -87,8 +95,9 @@ func TestHTTPRouteFlattening(t *testing.T) {
// write config entries // write config entries
proxyDefaults := &api.ProxyConfigEntry{ proxyDefaults := &api.ProxyConfigEntry{
Kind: api.ProxyDefaults, Kind: api.ProxyDefaults,
Name: api.ProxyConfigGlobal, Name: api.ProxyConfigGlobal,
Namespace: "", // proxy-defaults can only be set in the default namespace
Config: map[string]interface{}{ Config: map[string]interface{}{
"protocol": "http", "protocol": "http",
}, },
@ -106,6 +115,7 @@ func TestHTTPRouteFlattening(t *testing.T) {
Protocol: "http", Protocol: "http",
}, },
}, },
Namespace: namespace,
} }
routeOne := &api.HTTPRouteConfigEntry{ routeOne := &api.HTTPRouteConfigEntry{
@ -189,9 +199,14 @@ func TestHTTPRouteFlattening(t *testing.T) {
require.NoError(t, cluster.ConfigEntryWrite(routeTwo)) require.NoError(t, cluster.ConfigEntryWrite(routeTwo))
// create gateway service // create gateway service
gatewayService, err := libservice.NewGatewayService(context.Background(), gatewayName, "api", cluster.Agents[0], listenerPort) gwCfg := libservice.GatewayConfig{
Name: gatewayName,
Kind: "api",
Namespace: namespace,
}
gatewayService, err := libservice.NewGatewayService(context.Background(), gwCfg, cluster.Agents[0], listenerPort)
require.NoError(t, err) require.NoError(t, err)
libassert.CatalogServiceExists(t, client, gatewayName, nil) libassert.CatalogServiceExists(t, client, gatewayName, &api.QueryOptions{Namespace: namespace})
// make sure config entries have been properly created // make sure config entries have been properly created
checkGatewayConfigEntry(t, client, gatewayName, namespace) checkGatewayConfigEntry(t, client, gatewayName, namespace)
@ -201,8 +216,7 @@ func TestHTTPRouteFlattening(t *testing.T) {
// gateway resolves routes // gateway resolves routes
gatewayPort, err := gatewayService.GetPort(listenerPort) gatewayPort, err := gatewayService.GetPort(listenerPort)
require.NoError(t, err) require.NoError(t, err)
fmt.Println("Gateway Port: ", gatewayPort)
// route 2 with headers
// Same v2 path with and without header // Same v2 path with and without header
checkRoute(t, gatewayPort, "/v2", map[string]string{ checkRoute(t, gatewayPort, "/v2", map[string]string{
@ -233,7 +247,6 @@ func TestHTTPRouteFlattening(t *testing.T) {
checkRoute(t, gatewayPort, "/v2", map[string]string{ checkRoute(t, gatewayPort, "/v2", map[string]string{
"Host": "test.example", "Host": "test.example",
}, checkOptions{debug: false, statusCode: service1ResponseCode, testName: "service1, v2 path with v2 hostname"}) }, checkOptions{debug: false, statusCode: service1ResponseCode, testName: "service1, v2 path with v2 hostname"})
} }
func TestHTTPRoutePathRewrite(t *testing.T) { func TestHTTPRoutePathRewrite(t *testing.T) {
@ -252,12 +265,19 @@ func TestHTTPRoutePathRewrite(t *testing.T) {
barStatusCode := 201 barStatusCode := 201
fooPath := "/v1/foo" fooPath := "/v1/foo"
barPath := "/v1/bar" barPath := "/v1/bar"
namespace := getNamespace()
if namespace != "" {
ns := &api.Namespace{Name: namespace}
_, _, err := client.Namespaces().Create(ns, nil)
require.NoError(t, err)
}
fooService := createService(t, cluster, &libservice.ServiceOpts{ fooService := createService(t, cluster, &libservice.ServiceOpts{
Name: "foo", Name: "foo",
ID: "foo", ID: "foo",
HTTPPort: 8080, HTTPPort: 8080,
GRPCPort: 8081, GRPCPort: 8081,
Namespace: namespace,
}, []string{ }, []string{
// customizes response code so we can distinguish between which service is responding // customizes response code so we can distinguish between which service is responding
"-echo-debug-path", fooPath, "-echo-debug-path", fooPath,
@ -267,15 +287,15 @@ func TestHTTPRoutePathRewrite(t *testing.T) {
Name: "bar", Name: "bar",
ID: "bar", ID: "bar",
// TODO we can potentially get conflicts if these ports are the same // TODO we can potentially get conflicts if these ports are the same
HTTPPort: 8079, HTTPPort: 8079,
GRPCPort: 8078, GRPCPort: 8078,
Namespace: namespace,
}, []string{ }, []string{
"-echo-debug-path", barPath, "-echo-debug-path", barPath,
"-echo-server-default-params", fmt.Sprintf("status=%d", barStatusCode), "-echo-server-default-params", fmt.Sprintf("status=%d", barStatusCode),
}, },
) )
namespace := getNamespace()
gatewayName := randomName("gw", 16) gatewayName := randomName("gw", 16)
invalidRouteName := randomName("route", 16) invalidRouteName := randomName("route", 16)
validRouteName := randomName("route", 16) validRouteName := randomName("route", 16)
@ -284,8 +304,9 @@ func TestHTTPRoutePathRewrite(t *testing.T) {
// write config entries // write config entries
proxyDefaults := &api.ProxyConfigEntry{ proxyDefaults := &api.ProxyConfigEntry{
Kind: api.ProxyDefaults, Kind: api.ProxyDefaults,
Name: api.ProxyConfigGlobal, Name: api.ProxyConfigGlobal,
Namespace: "", // proxy-defaults can only be set in the default namespace
Config: map[string]interface{}{ Config: map[string]interface{}{
"protocol": "http", "protocol": "http",
}, },
@ -293,7 +314,7 @@ func TestHTTPRoutePathRewrite(t *testing.T) {
require.NoError(t, cluster.ConfigEntryWrite(proxyDefaults)) require.NoError(t, cluster.ConfigEntryWrite(proxyDefaults))
apiGateway := createGateway(gatewayName, "http", listenerPort) apiGateway := createGatewayConfigEntry(gatewayName, "http", namespace, listenerPort)
fooRoute := &api.HTTPRouteConfigEntry{ fooRoute := &api.HTTPRouteConfigEntry{
Kind: api.HTTPRoute, Kind: api.HTTPRoute,
@ -378,9 +399,14 @@ func TestHTTPRoutePathRewrite(t *testing.T) {
require.NoError(t, cluster.ConfigEntryWrite(barRoute)) require.NoError(t, cluster.ConfigEntryWrite(barRoute))
// create gateway service // create gateway service
gatewayService, err := libservice.NewGatewayService(context.Background(), gatewayName, "api", cluster.Agents[0], listenerPort) gwCfg := libservice.GatewayConfig{
Name: gatewayName,
Kind: "api",
Namespace: namespace,
}
gatewayService, err := libservice.NewGatewayService(context.Background(), gwCfg, cluster.Agents[0], listenerPort)
require.NoError(t, err) require.NoError(t, err)
libassert.CatalogServiceExists(t, client, gatewayName, nil) libassert.CatalogServiceExists(t, client, gatewayName, &api.QueryOptions{Namespace: namespace})
// make sure config entries have been properly created // make sure config entries have been properly created
checkGatewayConfigEntry(t, client, gatewayName, namespace) checkGatewayConfigEntry(t, client, gatewayName, namespace)
@ -402,7 +428,7 @@ func TestHTTPRoutePathRewrite(t *testing.T) {
// make sure foo is being sent to proper service // make sure foo is being sent to proper service
checkRoute(t, gatewayPort, fooUnrewritten+"/foo", map[string]string{ checkRoute(t, gatewayPort, fooUnrewritten+"/foo", map[string]string{
"Host": "test.foo", "Host": "test.foo",
}, checkOptions{debug: false, statusCode: fooStatusCode, testName: "foo service"}) }, checkOptions{debug: false, statusCode: fooStatusCode, testName: "foo service 2"})
// hit bar, making sure its been rewritten // hit bar, making sure its been rewritten
checkRoute(t, gatewayPort, barUnrewritten, map[string]string{ checkRoute(t, gatewayPort, barUnrewritten, map[string]string{
@ -413,7 +439,6 @@ func TestHTTPRoutePathRewrite(t *testing.T) {
checkRoute(t, gatewayPort, barUnrewritten+"/bar", map[string]string{ checkRoute(t, gatewayPort, barUnrewritten+"/bar", map[string]string{
"Host": "test.foo", "Host": "test.foo",
}, checkOptions{debug: false, statusCode: barStatusCode, testName: "bar service"}) }, checkOptions{debug: false, statusCode: barStatusCode, testName: "bar service"})
} }
func TestHTTPRouteParentRefChange(t *testing.T) { func TestHTTPRouteParentRefChange(t *testing.T) {
@ -431,23 +456,32 @@ func TestHTTPRouteParentRefChange(t *testing.T) {
// create cluster and service // create cluster and service
cluster := createCluster(t, listenerOnePort, listenerTwoPort) cluster := createCluster(t, listenerOnePort, listenerTwoPort)
client := cluster.Agents[0].GetClient() client := cluster.Agents[0].GetClient()
service := createService(t, cluster, &libservice.ServiceOpts{
Name: "service",
ID: "service",
HTTPPort: 8080,
GRPCPort: 8079,
}, []string{})
// getNamespace() should always return an empty string in Consul OSS // getNamespace() should always return an empty string in Consul OSS
namespace := getNamespace() namespace := getNamespace()
if namespace != "" {
ns := &api.Namespace{Name: namespace}
_, _, err := client.Namespaces().Create(ns, nil)
require.NoError(t, err)
}
service := createService(t, cluster, &libservice.ServiceOpts{
Name: "service",
ID: "service",
HTTPPort: 8080,
GRPCPort: 8079,
Namespace: namespace,
}, []string{})
gatewayOneName := randomName("gw1", 16) gatewayOneName := randomName("gw1", 16)
gatewayTwoName := randomName("gw2", 16) gatewayTwoName := randomName("gw2", 16)
routeName := randomName("route", 16) routeName := randomName("route", 16)
// write config entries // write config entries
proxyDefaults := &api.ProxyConfigEntry{ proxyDefaults := &api.ProxyConfigEntry{
Kind: api.ProxyDefaults, Kind: api.ProxyDefaults,
Name: api.ProxyConfigGlobal, Name: api.ProxyConfigGlobal,
Namespace: "", // proxy-defaults can only be set in the default namespace
Config: map[string]interface{}{ Config: map[string]interface{}{
"protocol": "http", "protocol": "http",
}, },
@ -467,6 +501,7 @@ func TestHTTPRouteParentRefChange(t *testing.T) {
Hostname: "test.foo", Hostname: "test.foo",
}, },
}, },
Namespace: namespace,
} }
require.NoError(t, cluster.ConfigEntryWrite(gatewayOne)) require.NoError(t, cluster.ConfigEntryWrite(gatewayOne))
require.Eventually(t, func() bool { require.Eventually(t, func() bool {
@ -481,9 +516,14 @@ func TestHTTPRouteParentRefChange(t *testing.T) {
}, time.Second*10, time.Second*1) }, time.Second*10, time.Second*1)
// create gateway service // create gateway service
gatewayOneService, err := libservice.NewGatewayService(context.Background(), gatewayOneName, "api", cluster.Agents[0], listenerOnePort) gwOneCfg := libservice.GatewayConfig{
Name: gatewayOneName,
Kind: "api",
Namespace: namespace,
}
gatewayOneService, err := libservice.NewGatewayService(context.Background(), gwOneCfg, cluster.Agents[0], listenerOnePort)
require.NoError(t, err) require.NoError(t, err)
libassert.CatalogServiceExists(t, client, gatewayOneName, nil) libassert.CatalogServiceExists(t, client, gatewayOneName, &api.QueryOptions{Namespace: namespace})
// create gateway config entry // create gateway config entry
gatewayTwo := &api.APIGatewayConfigEntry{ gatewayTwo := &api.APIGatewayConfigEntry{
@ -497,6 +537,7 @@ func TestHTTPRouteParentRefChange(t *testing.T) {
Hostname: "test.example", Hostname: "test.example",
}, },
}, },
Namespace: namespace,
} }
require.NoError(t, cluster.ConfigEntryWrite(gatewayTwo)) require.NoError(t, cluster.ConfigEntryWrite(gatewayTwo))
@ -513,9 +554,14 @@ func TestHTTPRouteParentRefChange(t *testing.T) {
}, time.Second*10, time.Second*1) }, time.Second*10, time.Second*1)
// create gateway service // create gateway service
gatewayTwoService, err := libservice.NewGatewayService(context.Background(), gatewayTwoName, "api", cluster.Agents[0], listenerTwoPort) gwTwoCfg := libservice.GatewayConfig{
Name: gatewayTwoName,
Kind: "api",
Namespace: namespace,
}
gatewayTwoService, err := libservice.NewGatewayService(context.Background(), gwTwoCfg, cluster.Agents[0], listenerTwoPort)
require.NoError(t, err) require.NoError(t, err)
libassert.CatalogServiceExists(t, client, gatewayTwoName, nil) libassert.CatalogServiceExists(t, client, gatewayTwoName, &api.QueryOptions{Namespace: namespace})
// create route to service, targeting first gateway // create route to service, targeting first gateway
route := &api.HTTPRouteConfigEntry{ route := &api.HTTPRouteConfigEntry{

View File

@ -5,9 +5,10 @@ import (
"testing" "testing"
"time" "time"
"github.com/hashicorp/go-version"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/hashicorp/go-version"
"github.com/hashicorp/consul/api" "github.com/hashicorp/consul/api"
libcluster "github.com/hashicorp/consul/test/integration/consul-container/libs/cluster" libcluster "github.com/hashicorp/consul/test/integration/consul-container/libs/cluster"
libservice "github.com/hashicorp/consul/test/integration/consul-container/libs/service" libservice "github.com/hashicorp/consul/test/integration/consul-container/libs/service"

View File

@ -10,6 +10,9 @@ import (
"time" "time"
"github.com/docker/go-connections/nat" "github.com/docker/go-connections/nat"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/hashicorp/consul/api" "github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/sdk/testutil/retry" "github.com/hashicorp/consul/sdk/testutil/retry"
libassert "github.com/hashicorp/consul/test/integration/consul-container/libs/assert" libassert "github.com/hashicorp/consul/test/integration/consul-container/libs/assert"
@ -17,8 +20,6 @@ import (
libservice "github.com/hashicorp/consul/test/integration/consul-container/libs/service" libservice "github.com/hashicorp/consul/test/integration/consul-container/libs/service"
"github.com/hashicorp/consul/test/integration/consul-container/libs/topology" "github.com/hashicorp/consul/test/integration/consul-container/libs/topology"
"github.com/hashicorp/consul/test/integration/consul-container/libs/utils" "github.com/hashicorp/consul/test/integration/consul-container/libs/utils"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
// These tests adapt BATS-based tests from test/integration/connect/case-ingress-gateway* // These tests adapt BATS-based tests from test/integration/connect/case-ingress-gateway*
@ -97,7 +98,11 @@ func TestIngressGateway_UpgradeToTarget_fromLatest(t *testing.T) {
}, },
})) }))
igw, err := libservice.NewGatewayService(context.Background(), nameIG, "ingress", cluster.Servers()[0]) gwCfg := libservice.GatewayConfig{
Name: nameIG,
Kind: "ingress",
}
igw, err := libservice.NewGatewayService(context.Background(), gwCfg, cluster.Servers()[0])
require.NoError(t, err) require.NoError(t, err)
t.Logf("created gateway: %#v", igw) t.Logf("created gateway: %#v", igw)
@ -226,7 +231,6 @@ func TestIngressGateway_UpgradeToTarget_fromLatest(t *testing.T) {
"Ingress should have set the client ip from dynamic Envoy variable") "Ingress should have set the client ip from dynamic Envoy variable")
assert.NotContains(t, string(body), "X-Bad-Req: true", assert.NotContains(t, string(body), "X-Bad-Req: true",
"Ingress should have removed the bad request header") "Ingress should have removed the bad request header")
}) })
t.Run("response header manipulation", func(t *testing.T) { t.Run("response header manipulation", func(t *testing.T) {
const params = "?header=x-bad-resp:true&header=x-existing-1:original&header=x-existing-2:original" const params = "?header=x-bad-resp:true&header=x-existing-1:original&header=x-existing-2:original"

View File

@ -432,7 +432,12 @@ func createAndRegisterStaticClientSidecarWith2Upstreams(c *cluster.Cluster, dest
} }
// Create a service and proxy instance // Create a service and proxy instance
clientConnectProxy, err := libservice.NewConnectService(context.Background(), fmt.Sprintf("%s-sidecar", libservice.StaticClientServiceName), libservice.StaticClientServiceName, []int{cluster.ServiceUpstreamLocalBindPort, cluster.ServiceUpstreamLocalBindPort2}, node) sidecarCfg := libservice.SidecarConfig{
Name: fmt.Sprintf("%s-sidecar", libservice.StaticClientServiceName),
ServiceID: libservice.StaticClientServiceName,
}
clientConnectProxy, err := libservice.NewConnectService(context.Background(), sidecarCfg, []int{cluster.ServiceUpstreamLocalBindPort, cluster.ServiceUpstreamLocalBindPort2}, node)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -4,11 +4,12 @@ import (
"context" "context"
"testing" "testing"
"github.com/stretchr/testify/require"
"github.com/hashicorp/consul/api" "github.com/hashicorp/consul/api"
libassert "github.com/hashicorp/consul/test/integration/consul-container/libs/assert" libassert "github.com/hashicorp/consul/test/integration/consul-container/libs/assert"
libcluster "github.com/hashicorp/consul/test/integration/consul-container/libs/cluster" libcluster "github.com/hashicorp/consul/test/integration/consul-container/libs/cluster"
libservice "github.com/hashicorp/consul/test/integration/consul-container/libs/service" libservice "github.com/hashicorp/consul/test/integration/consul-container/libs/service"
"github.com/stretchr/testify/require"
) )
func TestPeering_WanFedSecondaryDC(t *testing.T) { func TestPeering_WanFedSecondaryDC(t *testing.T) {
@ -36,7 +37,11 @@ func TestPeering_WanFedSecondaryDC(t *testing.T) {
t.Run("secondary dc can peer to alpha dc", func(t *testing.T) { t.Run("secondary dc can peer to alpha dc", func(t *testing.T) {
// Create the gateway // Create the gateway
_, err := libservice.NewGatewayService(context.Background(), "mesh", "mesh", c3.Servers()[0]) gwCfg := libservice.GatewayConfig{
Name: "mesh",
Kind: "mesh",
}
_, err := libservice.NewGatewayService(context.Background(), gwCfg, c3.Servers()[0])
require.NoError(t, err) require.NoError(t, err)
// Create the peering connection // Create the peering connection