Skip to content

Commit

Permalink
fix deprecated packages
Browse files Browse the repository at this point in the history
AmaliMatharaarachchi committed Jan 19, 2024
1 parent f07876c commit 023c1b6
Showing 10 changed files with 85 additions and 119 deletions.
2 changes: 1 addition & 1 deletion adapter/internal/discovery/xds/server.go
Original file line number Diff line number Diff line change
@@ -725,7 +725,7 @@ func UpdateAPICache(vHosts []string, newLabels []string, listener string, sectio
updatedLabelsMap[newLabel] = struct{}{}
}

routes, clusters, endpoints, err := oasParser.GetRoutesClustersEndpoints(adapterInternalAPI, nil,
routes, clusters, endpoints, err := oasParser.GetRoutesClustersEndpoints(&adapterInternalAPI, nil,
vHost, adapterInternalAPI.GetOrganizationID())

if err != nil {
2 changes: 1 addition & 1 deletion adapter/internal/oasparser/config_generator.go
Original file line number Diff line number Diff line change
@@ -38,7 +38,7 @@ import (

// GetRoutesClustersEndpoints generates the routes, clusters and endpoints (envoy)
// when the openAPI Json is provided. For websockets apiJsn created from api.yaml file is considered.
func GetRoutesClustersEndpoints(adapterInternalAPI model.AdapterInternalAPI, interceptorCerts map[string][]byte,
func GetRoutesClustersEndpoints(adapterInternalAPI *model.AdapterInternalAPI, interceptorCerts map[string][]byte,
vHost string, organizationID string) ([]*routev3.Route, []*clusterv3.Cluster, []*corev3.Address, error) {

routes, clusters, endpoints, err := envoy.CreateRoutesWithClusters(adapterInternalAPI, interceptorCerts,
6 changes: 3 additions & 3 deletions adapter/internal/oasparser/envoyconf/access_loggers.go
Original file line number Diff line number Diff line change
@@ -23,11 +23,11 @@ import (
grpc_accesslogv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/access_loggers/grpc/v3"
stream_accesslogv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/access_loggers/stream/v3"
"github.com/envoyproxy/go-control-plane/pkg/wellknown"
"github.com/golang/protobuf/ptypes"
"github.com/wso2/apk/adapter/config"
logger "github.com/wso2/apk/adapter/internal/loggers"
logging "github.com/wso2/apk/adapter/internal/logging"
"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/wrapperspb"
)

@@ -93,15 +93,15 @@ func getGRPCAccessLogConfigs(conf *config.Config) *config_access_logv3.AccessLog
CommonConfig: &grpc_accesslogv3.CommonGrpcAccessLogConfig{
TransportApiVersion: corev3.ApiVersion_V3,
LogName: grpcAccessLogLogName,
BufferFlushInterval: ptypes.DurationProto(conf.Analytics.Adapter.BufferFlushInterval),
BufferFlushInterval: durationpb.New(conf.Analytics.Adapter.BufferFlushInterval),
BufferSizeBytes: wrapperspb.UInt32(conf.Analytics.Adapter.BufferSizeBytes),
GrpcService: &corev3.GrpcService{
TargetSpecifier: &corev3.GrpcService_EnvoyGrpc_{
EnvoyGrpc: &corev3.GrpcService_EnvoyGrpc{
ClusterName: accessLoggerClusterName,
},
},
Timeout: ptypes.DurationProto(conf.Analytics.Adapter.GRPCRequestTimeout),
Timeout: durationpb.New(conf.Analytics.Adapter.GRPCRequestTimeout),
},
},
}
8 changes: 2 additions & 6 deletions adapter/internal/oasparser/envoyconf/compression_filter.go
Original file line number Diff line number Diff line change
@@ -82,12 +82,8 @@ func getCompressorFilter() (*hcmv3.HttpFilter, error) {
var requestDirectionContentTypes []string
var libraryConfig protoreflect.ProtoMessage

for _, val := range configRead.Envoy.Filters.Compression.ResponseDirection.ContentType {
responseDirectionContentTypes = append(responseDirectionContentTypes, val)
}
for _, val := range configRead.Envoy.Filters.Compression.RequestDirection.ContentType {
requestDirectionContentTypes = append(requestDirectionContentTypes, val)
}
responseDirectionContentTypes = append(responseDirectionContentTypes, configRead.Envoy.Filters.Compression.ResponseDirection.ContentType...)
requestDirectionContentTypes = append(requestDirectionContentTypes, configRead.Envoy.Filters.Compression.RequestDirection.ContentType...)

compressionLibrary := strings.ToLower(configRead.Envoy.Filters.Compression.Library)
if compressionLibrary == "gzip" {
7 changes: 3 additions & 4 deletions adapter/internal/oasparser/envoyconf/http_filters.go
Original file line number Diff line number Diff line change
@@ -39,11 +39,10 @@ import (
"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/durationpb"

"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes"
"github.com/wso2/apk/adapter/config"
logger "github.com/wso2/apk/adapter/internal/loggers"
logging "github.com/wso2/apk/adapter/internal/logging"
"google.golang.org/protobuf/proto"

"github.com/golang/protobuf/ptypes/any"
)
@@ -178,7 +177,7 @@ func getRateLimitFilter() *hcmv3.HttpFilter {
},
},
}
ext, err2 := ptypes.MarshalAny(rateLimit)
ext, err2 := anypb.New(rateLimit)
if err2 != nil {
logger.LoggerOasparser.ErrorC(logging.PrintError(logging.Error2241, logging.MAJOR, "Error occurred while parsing ratelimit filter config. Error: %s", err2.Error()))
}
@@ -207,7 +206,7 @@ func getExtAuthzHTTPFilter() *hcmv3.HttpFilter {
ClusterName: extAuthzClusterName,
},
},
Timeout: ptypes.DurationProto(conf.Envoy.EnforcerResponseTimeoutInSeconds * time.Second),
Timeout: durationpb.New(conf.Envoy.EnforcerResponseTimeoutInSeconds * time.Second),
InitialMetadata: []*corev3.HeaderValue{
{
Key: "x-request-id",
1 change: 0 additions & 1 deletion adapter/internal/oasparser/envoyconf/internal_dtos.go
Original file line number Diff line number Diff line change
@@ -33,7 +33,6 @@ type routeCreateParams struct {
endpointBasePath string
resource *model.Resource
clusterName string
endpoints *model.EndpointCluster
authHeader string
requestInterceptor map[string]model.InterceptEndpoint
responseInterceptor map[string]model.InterceptEndpoint
60 changes: 28 additions & 32 deletions adapter/internal/oasparser/envoyconf/listener.go
Original file line number Diff line number Diff line change
@@ -32,13 +32,11 @@ import (
tlsv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/transport_sockets/tls/v3"
metadatav3 "github.com/envoyproxy/go-control-plane/envoy/type/metadata/v3"
"github.com/envoyproxy/go-control-plane/pkg/wellknown"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/wrappers"

"github.com/wso2/apk/adapter/config"
"github.com/wso2/apk/adapter/internal/discovery/xds/common"
"github.com/wso2/apk/adapter/internal/loggers"
logger "github.com/wso2/apk/adapter/internal/loggers"
"github.com/wso2/apk/adapter/internal/oasparser/model"
"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/durationpb"
@@ -76,16 +74,16 @@ func CreateRoutesConfigForRds(vHosts []*routev3.VirtualHost, httpListeners strin
// as inline records (base64 encoded).
func CreateListenerByGateway(gateway *gwapiv1b1.Gateway, resolvedListenerCerts map[string]map[string][]byte, gwLuaScript string) []*listenerv3.Listener {
conf := config.ReadConfigs()
// Prepare a map that contains all the listerners identified in all of the gateways that reconciled so far.
// Prepare a map that contains all the listerners identified in all of the gateways that reconciled so far.
// This map contains port - listeners per protocol with port
protocolListenerMap := make(map[gwapiv1b1.ProtocolType]map[uint32][]gwapiv1b1.Listener)
for _, listener := range gateway.Spec.Listeners {
port := uint32(listener.Port)
if protocolListenerMap[listener.Protocol] == nil {
protocolListenerMap[listener.Protocol] = make(map[uint32][]gwapiv1b1.Listener)
protocolListenerMap[listener.Protocol] = make(map[uint32][]gwapiv1b1.Listener)
}
if protocolListenerMap[listener.Protocol][port] == nil {
protocolListenerMap[listener.Protocol][port] = []gwapiv1b1.Listener{}
protocolListenerMap[listener.Protocol][port] = []gwapiv1b1.Listener{}
}
protocolListenerMap[listener.Protocol][port] = append(protocolListenerMap[listener.Protocol][port], listener)
}
@@ -110,12 +108,12 @@ func CreateListenerByGateway(gateway *gwapiv1b1.Gateway, resolvedListenerCerts m
function envoy_on_response(response_handle)
end`)
}
listenerName = common.GetEnvoyListenerName(string(protocol), port)
listenerName = common.GetEnvoyListenerName(string(protocol), port)
filterChainMatch := &listenerv3.FilterChainMatch{
ServerNames: []string{string(*listenerObj.Hostname)},
}
var transportSocket *corev3.TransportSocket
if (protocol == gwapiv1b1.HTTPSProtocolType) {
if protocol == gwapiv1b1.HTTPSProtocolType {
publicCertData := resolvedListenerCerts[string(listenerObj.Name)]["tls.crt"]
privateKeyData := resolvedListenerCerts[string(listenerObj.Name)]["tls.key"]
var tlsFilter *tlsv3.DownstreamTlsContext
@@ -154,7 +152,7 @@ func CreateListenerByGateway(gateway *gwapiv1b1.Gateway, resolvedListenerCerts m

marshalledTLSFilter, err := anypb.New(tlsFilter)
if err != nil {
logger.LoggerOasparser.Fatal("Error while Marshalling the downstream TLS Context for the configuration.")
loggers.LoggerOasparser.Fatal("Error while Marshalling the downstream TLS Context for the configuration.")
}

transportSocket = &corev3.TransportSocket{
@@ -164,7 +162,7 @@ func CreateListenerByGateway(gateway *gwapiv1b1.Gateway, resolvedListenerCerts m
},
}
}

var filters []*listenerv3.Filter
manager := &hcmv3.HttpConnectionManager{
CodecType: getListenerCodecType(conf.Envoy.ListenerCodecType),
@@ -190,11 +188,11 @@ func CreateListenerByGateway(gateway *gwapiv1b1.Gateway, resolvedListenerCerts m
LocalReplyConfig: &hcmv3.LocalReplyConfig{
Mappers: getErrorResponseMappers(),
},
RequestTimeout: ptypes.DurationProto(conf.Envoy.Connection.Timeouts.RequestTimeoutInSeconds * time.Second), // default disabled
RequestHeadersTimeout: ptypes.DurationProto(conf.Envoy.Connection.Timeouts.RequestHeadersTimeoutInSeconds * time.Second), // default disabled
StreamIdleTimeout: ptypes.DurationProto(conf.Envoy.Connection.Timeouts.StreamIdleTimeoutInSeconds * time.Second), // Default 5 mins
RequestTimeout: durationpb.New(conf.Envoy.Connection.Timeouts.RequestTimeoutInSeconds * time.Second), // default disabled
RequestHeadersTimeout: durationpb.New(conf.Envoy.Connection.Timeouts.RequestHeadersTimeoutInSeconds * time.Second), // default disabled
StreamIdleTimeout: durationpb.New(conf.Envoy.Connection.Timeouts.StreamIdleTimeoutInSeconds * time.Second), // Default 5 mins
CommonHttpProtocolOptions: &corev3.HttpProtocolOptions{
IdleTimeout: ptypes.DurationProto(conf.Envoy.Connection.Timeouts.IdleTimeoutInSeconds * time.Second), // Default 1 hr
IdleTimeout: durationpb.New(conf.Envoy.Connection.Timeouts.IdleTimeoutInSeconds * time.Second), // Default 1 hr
},
HttpProtocolOptions: &corev3.Http1ProtocolOptions{
EnableTrailers: config.GetWireLogConfig().LogTrailersEnabled,
@@ -213,7 +211,7 @@ func CreateListenerByGateway(gateway *gwapiv1b1.Gateway, resolvedListenerCerts m
manager.Tracing = tracing
manager.GenerateRequestId = &wrappers.BoolValue{Value: conf.Tracing.Enabled}
} else {
logger.LoggerOasparser.Errorf("Failed to initialize tracing for %s. Router tracing will be disabled. Error: %s",
loggers.LoggerOasparser.Errorf("Failed to initialize tracing for %s. Router tracing will be disabled. Error: %s",
TracerTypeOtlp, err)
conf.Tracing.Enabled = false
}
@@ -222,7 +220,7 @@ func CreateListenerByGateway(gateway *gwapiv1b1.Gateway, resolvedListenerCerts m
manager.Tracing = tracing
manager.GenerateRequestId = &wrappers.BoolValue{Value: conf.Tracing.Enabled}
} else {
logger.LoggerOasparser.Errorf("Failed to initialize tracing for %s. Router tracing will be disabled. Error: %s",
loggers.LoggerOasparser.Errorf("Failed to initialize tracing for %s. Router tracing will be disabled. Error: %s",
conf.Tracing.Type, err)
conf.Tracing.Enabled = false
}
@@ -231,7 +229,7 @@ func CreateListenerByGateway(gateway *gwapiv1b1.Gateway, resolvedListenerCerts m

pbst, err := anypb.New(manager)
if err != nil {
logger.LoggerOasparser.Fatal(err)
loggers.LoggerOasparser.Fatal(err)
}
connectionManagerFilterP := listenerv3.Filter{
Name: wellknown.HTTPConnectionManager,
@@ -250,7 +248,7 @@ func CreateListenerByGateway(gateway *gwapiv1b1.Gateway, resolvedListenerCerts m
})
} else {
filterChains = append(filterChains, &listenerv3.FilterChain{
Filters: filters,
Filters: filters,
})
}

@@ -273,7 +271,7 @@ func CreateListenerByGateway(gateway *gwapiv1b1.Gateway, resolvedListenerCerts m
tlsInspector := &tlsInspectorv3.TlsInspector{}
marshalledListenerFilter, err := anypb.New(tlsInspector)
if err != nil {
logger.LoggerOasparser.Fatal("Error while Marshalling the TlsInspector for the configuration.")
loggers.LoggerOasparser.Fatal("Error while Marshalling the TlsInspector for the configuration.")
}

listenerFilters := []*listenerv3.ListenerFilter{
@@ -293,9 +291,9 @@ func CreateListenerByGateway(gateway *gwapiv1b1.Gateway, resolvedListenerCerts m
ListenerFilters: listenerFilters,
FilterChains: filterChains,
}
logger.LoggerOasparser.Infof("Secured Listener is added. %s : %d", listenerHostAddress, port)
loggers.LoggerOasparser.Infof("Secured Listener is added. %s : %d", listenerHostAddress, port)
} else {
logger.LoggerOasparser.Info("No SecuredListenerPort is included.")
loggers.LoggerOasparser.Info("No SecuredListenerPort is included.")
}

if protocol == gwapiv1b1.HTTPProtocolType {
@@ -317,19 +315,19 @@ func CreateListenerByGateway(gateway *gwapiv1b1.Gateway, resolvedListenerCerts m
},
FilterChains: filterChains,
}
logger.LoggerOasparser.Infof("Non-secured Listener is added. %s : %d", listenerHostAddress, port)
loggers.LoggerOasparser.Infof("Non-secured Listener is added. %s : %d", listenerHostAddress, port)
} else {
logger.LoggerOasparser.Info("No Non-securedListenerPort is included.")
loggers.LoggerOasparser.Info("No Non-securedListenerPort is included.")
}

if listeners == nil {
err := errors.New("No Listeners are configured as no port value is mentioned under securedListenerPort or ListenerPort")
logger.LoggerOasparser.Fatal(err)
err := errors.New("no Listeners are configured as no port value is mentioned under securedListenerPort or ListenerPort")
loggers.LoggerOasparser.Fatal(err)
}
listenerList = append(listenerList, listener)
}
}
logger.LoggerOasparser.Infof("Listener list size. %+v", len(listenerList))
loggers.LoggerOasparser.Infof("Listener list size. %+v", len(listenerList))
return listenerList
}

@@ -410,8 +408,7 @@ func CreateVirtualHosts(vhostToRouteArrayMap map[string][]*routev3.Route, custom
// generateTLSCert generates the TLS Certiificate with given private key filepath and the corresponding public Key filepath.
// The files should be mounted to the router container unless the default cert is used.
func generateTLSCert(privateKeyPath string, publicKeyPath string) *tlsv3.TlsCertificate {
var tlsCert tlsv3.TlsCertificate
tlsCert = tlsv3.TlsCertificate{
tlsCert := tlsv3.TlsCertificate{
PrivateKey: &corev3.DataSource{
Specifier: &corev3.DataSource_Filename{
Filename: privateKeyPath,
@@ -428,8 +425,7 @@ func generateTLSCert(privateKeyPath string, publicKeyPath string) *tlsv3.TlsCert

// generate TLS certs as inline strings
func generateTLSCertWithStr(privateKey string, publicKey string) *tlsv3.TlsCertificate {
var tlsCert tlsv3.TlsCertificate
tlsCert = tlsv3.TlsCertificate{
tlsCert := tlsv3.TlsCertificate{
PrivateKey: &corev3.DataSource{
Specifier: &corev3.DataSource_InlineString{
InlineString: privateKey,
@@ -449,12 +445,12 @@ func getZipkinTracing(conf *config.Config) (*hcmv3.HttpConnectionManager_Tracing
var maxPathLength uint32

if endpoint = conf.Tracing.ConfigProperties[tracerEndpoint]; len(endpoint) <= 0 {
return nil, errors.New("Invalid endpoint path provided for tracing endpoint")
return nil, errors.New("invalid endpoint path provided for tracing endpoint")
}
if length, err := strconv.ParseUint(conf.Tracing.ConfigProperties[tracerMaxPathLength], 10, 32); err == nil {
maxPathLength = uint32(length)
} else {
return nil, errors.New("Invalid max path length provided for tracing endpoint")
return nil, errors.New("invalid max path length provided for tracing endpoint")
}

providerConf := &envoy_config_trace_v3.ZipkinConfig{
@@ -509,7 +505,7 @@ func getTracingOTLP(conf *config.Config) (*hcmv3.HttpConnectionManager_Tracing,
connectionTimeout = uint32(timeout)
} else {
connectionTimeout = 20
logger.LoggerOasparser.Infof("Setting up default connection timeout for tracing endpoint as %d seconds", connectionTimeout)
loggers.LoggerOasparser.Infof("Setting up default connection timeout for tracing endpoint as %d seconds", connectionTimeout)
}

providerConf := &envoy_config_trace_v3.OpenTelemetryConfig{
8 changes: 3 additions & 5 deletions adapter/internal/oasparser/envoyconf/routes_configs.go
Original file line number Diff line number Diff line change
@@ -29,12 +29,12 @@ import (
extAuthService "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/ext_authz/v3"
envoy_type_matcherv3 "github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3"
"github.com/envoyproxy/go-control-plane/pkg/wellknown"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes/any"
logger "github.com/wso2/apk/adapter/internal/loggers"
"github.com/wso2/apk/adapter/internal/oasparser/constants"
"github.com/wso2/apk/adapter/internal/oasparser/model"
opConstants "github.com/wso2/apk/adapter/internal/operator/constants"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/wrapperspb"
@@ -315,12 +315,10 @@ func generateFilterConfigToSkipEnforcer() map[string]*anypb.Any {
},
}

b := proto.NewBuffer(nil)
b.SetDeterministic(true)
_ = b.Marshal(&perFilterConfig)
data, _ := proto.Marshal(&perFilterConfig)
filter := &any.Any{
TypeUrl: extAuthzPerRouteName,
Value: b.Bytes(),
Value: data,
}

return map[string]*any.Any{
86 changes: 32 additions & 54 deletions adapter/internal/oasparser/envoyconf/routes_with_clusters.go
Original file line number Diff line number Diff line change
@@ -42,7 +42,6 @@ import (
lua "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/lua/v3"
tlsv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/transport_sockets/tls/v3"
upstreams "github.com/envoyproxy/go-control-plane/envoy/extensions/upstreams/http/v3"
upstreams_http_v3 "github.com/envoyproxy/go-control-plane/envoy/extensions/upstreams/http/v3"
envoy_type_matcherv3 "github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3"
"github.com/envoyproxy/go-control-plane/pkg/wellknown"

@@ -55,10 +54,9 @@ import (
"github.com/wso2/apk/adapter/internal/svcdiscovery"
dpv1alpha2 "github.com/wso2/apk/common-go-libs/apis/dp/v1alpha2"

"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/any"
"github.com/golang/protobuf/ptypes/wrappers"
"google.golang.org/protobuf/proto"
gwapiv1b1 "sigs.k8s.io/gateway-api/apis/v1beta1"
)

@@ -93,7 +91,7 @@ const (
// If a resource has resource level endpoint, it create another cluster and
// link it. If resources doesn't has resource level endpoints, those clusters are linked
// to the api level clusters.
func CreateRoutesWithClusters(adapterInternalAPI model.AdapterInternalAPI, interceptorCerts map[string][]byte, vHost string, organizationID string) (routesP []*routev3.Route,
func CreateRoutesWithClusters(adapterInternalAPI *model.AdapterInternalAPI, interceptorCerts map[string][]byte, vHost string, organizationID string) (routesP []*routev3.Route,
clustersP []*clusterv3.Cluster, addressesP []*corev3.Address, err error) {
var (
routes []*routev3.Route
@@ -128,7 +126,7 @@ func CreateRoutesWithClusters(adapterInternalAPI model.AdapterInternalAPI, inter
}
routeP := CreateAPIDefinitionEndpoint(adapterInternalAPI.GetXWso2Basepath(), vHost, methods, false, adapterInternalAPI.GetVersion(), adapterInternalAPI.GetAPIDefinitionEndpoint())
routes = append(routes, routeP)
if (&adapterInternalAPI).IsDefaultVersion {
if (adapterInternalAPI).IsDefaultVersion {
defaultDefRoutes := CreateAPIDefinitionEndpoint(adapterInternalAPI.GetXWso2Basepath(), vHost, methods, true, adapterInternalAPI.GetVersion(), adapterInternalAPI.GetAPIDefinitionEndpoint())
routes = append(routes, defaultDefRoutes)
}
@@ -182,7 +180,7 @@ func CreateRoutesWithClusters(adapterInternalAPI model.AdapterInternalAPI, inter
}
gqlop := model.NewOperationWithPolicies("POST", policies)
resource := model.CreateMinimalResource(adapterInternalAPI.GetXWso2Basepath(), []*model.Operation{gqlop}, "", adapterInternalAPI.Endpoints, true, gwapiv1b1.PathMatchExact)
routesP, err := createRoutes(genRouteCreateParams(&adapterInternalAPI, &resource, vHost, basePath, clusterName, nil,
routesP, err := createRoutes(genRouteCreateParams(adapterInternalAPI, &resource, vHost, basePath, clusterName, nil,
nil, organizationID, false, false))
if err != nil {
logger.LoggerXds.ErrorC(logging.PrintError(logging.Error2231, logging.MAJOR,
@@ -218,17 +216,19 @@ func CreateRoutesWithClusters(adapterInternalAPI model.AdapterInternalAPI, inter
interceptorCerts, vHost, organizationID, apiRequestInterceptor, apiResponseInterceptor, resource)
clusters = append(clusters, clustersI...)
endpoints = append(endpoints, endpointsI...)
routeParams := genRouteCreateParams(&adapterInternalAPI, resource, vHost, basePath, clusterName, *operationalReqInterceptors, *operationalRespInterceptorVal, organizationID,
routeParams := genRouteCreateParams(adapterInternalAPI, resource, vHost, basePath, clusterName, *operationalReqInterceptors, *operationalRespInterceptorVal, organizationID,
false, false)

routeP, err := createRoutes(routeParams)
if err != nil {
logger.LoggerXds.ErrorC(logging.PrintError(logging.Error2231, logging.MAJOR, "Error while creating routes for API %s %s for path: %s Error: %s", adapterInternalAPI.GetTitle(), adapterInternalAPI.GetVersion(), resource.GetPath(), err.Error()))
logger.LoggerXds.ErrorC(logging.PrintError(logging.Error2231, logging.MAJOR,
"Error while creating routes for API %s %s for path: %s Error: %s", adapterInternalAPI.GetTitle(),
adapterInternalAPI.GetVersion(), resource.GetPath(), err.Error()))
return nil, nil, nil, fmt.Errorf("error while creating routes. %v", err)
}
routes = append(routes, routeP...)
if (&adapterInternalAPI).IsDefaultVersion {
defaultRoutes, errDefaultPath := createRoutes(genRouteCreateParams(&adapterInternalAPI, resource, vHost, basePath, clusterName, *operationalReqInterceptors, *operationalRespInterceptorVal, organizationID,
if adapterInternalAPI.IsDefaultVersion {
defaultRoutes, errDefaultPath := createRoutes(genRouteCreateParams(adapterInternalAPI, resource, vHost, basePath, clusterName, *operationalReqInterceptors, *operationalRespInterceptorVal, organizationID,
false, true))
if errDefaultPath != nil {
logger.LoggerXds.ErrorC(logging.PrintError(logging.Error2231, logging.MAJOR, "Error while creating routes for API %s %s for path: %s Error: %s", adapterInternalAPI.GetTitle(), adapterInternalAPI.GetVersion(), removeFirstOccurrence(resource.GetPath(), adapterInternalAPI.GetVersion()), errDefaultPath.Error()))
@@ -346,7 +346,7 @@ func CreateRateLimitCluster() (*clusterv3.Cluster, []*corev3.Address, error) {
},
},
}
marshalledTLSContext, err := ptypes.MarshalAny(upstreamTLSContext)
marshalledTLSContext, err := anypb.New(upstreamTLSContext)
if err != nil {
return nil, nil, errors.New("internal Error while marshalling the upstream TLS Context")
}
@@ -487,10 +487,10 @@ func processEndpoints(clusterName string, clusterDetails *model.EndpointCluster,
}
conf := config.ReadConfigs()

httpProtocolOptions := &upstreams_http_v3.HttpProtocolOptions{
UpstreamProtocolOptions: &upstreams_http_v3.HttpProtocolOptions_ExplicitHttpConfig_{
ExplicitHttpConfig: &upstreams_http_v3.HttpProtocolOptions_ExplicitHttpConfig{
ProtocolConfig: &upstreams_http_v3.HttpProtocolOptions_ExplicitHttpConfig_HttpProtocolOptions{
httpProtocolOptions := &upstreams.HttpProtocolOptions{
UpstreamProtocolOptions: &upstreams.HttpProtocolOptions_ExplicitHttpConfig_{
ExplicitHttpConfig: &upstreams.HttpProtocolOptions_ExplicitHttpConfig{
ProtocolConfig: &upstreams.HttpProtocolOptions_ExplicitHttpConfig_HttpProtocolOptions{
HttpProtocolOptions: &corev3.Http1ProtocolOptions{
EnableTrailers: config.GetWireLogConfig().LogTrailersEnabled,
},
@@ -500,9 +500,9 @@ func processEndpoints(clusterName string, clusterDetails *model.EndpointCluster,
}

if clusterDetails.HTTP2BackendEnabled {
httpProtocolOptions.UpstreamProtocolOptions = &upstreams_http_v3.HttpProtocolOptions_ExplicitHttpConfig_{
ExplicitHttpConfig: &upstreams_http_v3.HttpProtocolOptions_ExplicitHttpConfig{
ProtocolConfig: &upstreams_http_v3.HttpProtocolOptions_ExplicitHttpConfig_Http2ProtocolOptions{
httpProtocolOptions.UpstreamProtocolOptions = &upstreams.HttpProtocolOptions_ExplicitHttpConfig_{
ExplicitHttpConfig: &upstreams.HttpProtocolOptions_ExplicitHttpConfig{
ProtocolConfig: &upstreams.HttpProtocolOptions_ExplicitHttpConfig_Http2ProtocolOptions{
Http2ProtocolOptions: &corev3.Http2ProtocolOptions{
HpackTableSize: &wrapperspb.UInt32Value{
Value: conf.Envoy.Upstream.HTTP2.HpackTableSize,
@@ -747,13 +747,11 @@ func createRoutes(params *routeCreateParams) (routes []*routev3.Route, err error
},
}

b := proto.NewBuffer(nil)
b.SetDeterministic(true)
_ = b.Marshal(&extAuthPerFilterConfig)
data, _ := proto.Marshal(&extAuthPerFilterConfig)

extAuthzFilter := &any.Any{
TypeUrl: extAuthzPerRouteName,
Value: b.Bytes(),
Value: data,
}

var luaPerFilterConfig lua.LuaPerRoute
@@ -817,13 +815,11 @@ func createRoutes(params *routeCreateParams) (routes []*routev3.Route, err error
}
}

luaMarshelled := proto.NewBuffer(nil)
luaMarshelled.SetDeterministic(true)
_ = luaMarshelled.Marshal(&luaPerFilterConfig)
data, _ = proto.Marshal(&luaPerFilterConfig)

luaFilter := &any.Any{
TypeUrl: luaPerRouteName,
Value: luaMarshelled.Bytes(),
Value: data,
}

corsFilter, _ := anypb.New(corsPolicy)
@@ -1154,12 +1150,10 @@ func CreateAPIDefinitionRoute(basePath string, vHost string, methods []string, i
},
}

b := proto.NewBuffer(nil)
b.SetDeterministic(true)
_ = b.Marshal(&perFilterConfig)
data, _ := proto.Marshal(&perFilterConfig)
filter := &any.Any{
TypeUrl: extAuthzPerRouteName,
Value: b.Bytes(),
Value: data,
}

directClusterSpecifier := &routev3.RouteAction_Cluster{
@@ -1228,12 +1222,10 @@ func CreateAPIDefinitionEndpoint(basePath string, vHost string, methods []string
},
}

b := proto.NewBuffer(nil)
b.SetDeterministic(true)
_ = b.Marshal(&perFilterConfig)
data, _ := proto.Marshal(&perFilterConfig)
filter := &any.Any{
TypeUrl: extAuthzPerRouteName,
Value: b.Bytes(),
Value: data,
}

directClusterSpecifier := &routev3.RouteAction_Cluster{
@@ -1290,12 +1282,10 @@ func CreateHealthEndpoint() *routev3.Route {
},
}

b := proto.NewBuffer(nil)
b.SetDeterministic(true)
_ = b.Marshal(&perFilterConfig)
data, _ := proto.Marshal(&perFilterConfig)
filter := &any.Any{
TypeUrl: extAuthzPerRouteName,
Value: b.Bytes(),
Value: data,
}

router = routev3.Route{
@@ -1345,12 +1335,10 @@ func CreateReadyEndpoint() *routev3.Route {
},
}

b := proto.NewBuffer(nil)
b.SetDeterministic(true)
_ = b.Marshal(&perFilterConfig)
data, _ := proto.Marshal(&perFilterConfig)
filter := &any.Any{
TypeUrl: extAuthzPerRouteName,
Value: b.Bytes(),
Value: data,
}

router = routev3.Route{
@@ -1596,17 +1584,7 @@ func getMaxStreamDuration(apiType string) *routev3.RouteAction_MaxStreamDuration
return maxStreamDuration
}

func getDefaultVersionBasepath(basePath string, version string) string {
// Following is used to replace only the version when basepath = /foo/v2 and version = v2 and context => /foo/v2/v2
indexOfVersionString := strings.LastIndex(basePath, "/"+version)
context := strings.Replace(basePath, "/"+version, "", indexOfVersionString)

// Having ?: in the regex below, avoids this regex acting as a capturing group. Without this the basepath
// would again be added in the locations of path variables when sending the request to backend.
return fmt.Sprintf("(?:%s|%s)", basePath, context)
}

func createInterceptorAPIClusters(adapterInternalAPI model.AdapterInternalAPI, interceptorCerts map[string][]byte, vHost string, organizationID string) (clustersP []*clusterv3.Cluster,
func createInterceptorAPIClusters(adapterInternalAPI *model.AdapterInternalAPI, interceptorCerts map[string][]byte, vHost string, organizationID string) (clustersP []*clusterv3.Cluster,
addressesP []*corev3.Address, apiRequestInterceptorEndpoint *model.InterceptEndpoint, apiResponseInterceptorEndpoint *model.InterceptEndpoint) {
var (
clusters []*clusterv3.Cluster
@@ -1652,7 +1630,7 @@ func createInterceptorAPIClusters(adapterInternalAPI model.AdapterInternalAPI, i
return clusters, endpoints, &apiRequestInterceptor, &apiResponseInterceptor
}

func createInterceptorResourceClusters(adapterInternalAPI model.AdapterInternalAPI, interceptorCerts map[string][]byte, vHost string, organizationID string,
func createInterceptorResourceClusters(adapterInternalAPI *model.AdapterInternalAPI, interceptorCerts map[string][]byte, vHost string, organizationID string,
apiRequestInterceptor *model.InterceptEndpoint, apiResponseInterceptor *model.InterceptEndpoint, resource *model.Resource) (clustersP []*clusterv3.Cluster, addressesP []*corev3.Address,
operationalReqInterceptorsEndpoint *map[string]model.InterceptEndpoint, operationalRespInterceptorValEndpoint *map[string]model.InterceptEndpoint) {
var (
24 changes: 12 additions & 12 deletions adapter/internal/oasparser/envoyconf/routes_with_clusters_test.go
Original file line number Diff line number Diff line change
@@ -132,9 +132,9 @@ func TestCreateRoutesWithClustersWithExactAndRegularExpressionRules(t *testing.T
apiState.ProdHTTPRoute = &httpRouteState

adapterInternalAPI, labels, err := synchronizer.GenerateAdapterInternalAPI(apiState, &httpRouteState, constants.Production)
assert.Equal(t, map[string]struct{}{"default-gateway": struct{}{}}, labels, "Labels are incorrect.")
assert.Equal(t, map[string]struct{}{"default-gateway": {}}, labels, "Labels are incorrect.")
assert.Nil(t, err, "Error should not be present when apiState is converted to a AdapterInternalAPI object")
routes, clusters, _, _ := envoy.CreateRoutesWithClusters(*adapterInternalAPI, nil, "prod.gw.wso2.com", "carbon.super")
routes, clusters, _, _ := envoy.CreateRoutesWithClusters(adapterInternalAPI, nil, "prod.gw.wso2.com", "carbon.super")
assert.Equal(t, 3, len(clusters), "Number of production clusters created is incorrect.")

exactPathCluster := clusters[1]
@@ -185,7 +185,7 @@ func TestGenerateAdapterInternalAPIForDefaultCase(t *testing.T) {
httpRouteState = *apiState.ProdHTTPRoute
xds.SanitizeGateway("default-gateway", true)
adapterInternalAPI, labels, err := synchronizer.GenerateAdapterInternalAPI(apiState, &httpRouteState, constants.Production)
assert.Equal(t, map[string]struct{}{"default-gateway": struct{}{}}, labels, "Labels are incorrect.")
assert.Equal(t, map[string]struct{}{"default-gateway": {}}, labels, "Labels are incorrect.")
assert.Nil(t, err, "Error should not be present when apiState is converted to a AdapterInternalAPI object")
assert.Equal(t, "Default", adapterInternalAPI.GetEnvironment(), "Environment is incorrect.")
}
@@ -199,7 +199,7 @@ func TestGenerateAdapterInternalAPIForSpecificEnvironment(t *testing.T) {
xds.SanitizeGateway("default-gateway", true)

adapterInternalAPI, labels, err := synchronizer.GenerateAdapterInternalAPI(apiState, &httpRouteState, constants.Production)
assert.Equal(t, map[string]struct{}{"default-gateway": struct{}{}}, labels, "Labels are incorrect.")
assert.Equal(t, map[string]struct{}{"default-gateway": {}}, labels, "Labels are incorrect.")
assert.Nil(t, err, "Error should not be present when apiState is converted to a AdapterInternalAPI object")
assert.Equal(t, "dev", adapterInternalAPI.GetEnvironment(), "Environment is incorrect.")
}
@@ -349,9 +349,9 @@ func TestCreateRoutesWithClustersWithMultiplePathPrefixRules(t *testing.T) {
xds.SanitizeGateway("default-gateway", true)

adapterInternalAPI, labels, err := synchronizer.GenerateAdapterInternalAPI(apiState, &httpRouteState, constants.Production)
assert.Equal(t, map[string]struct{}{"default-gateway": struct{}{}}, labels, "Labels are incorrect.")
assert.Equal(t, map[string]struct{}{"default-gateway": {}}, labels, "Labels are incorrect.")
assert.Nil(t, err, "Error should not be present when apiState is converted to a AdapterInternalAPI object")
routes, clusters, _, _ := envoy.CreateRoutesWithClusters(*adapterInternalAPI, nil, "prod.gw.wso2.com", "carbon.super")
routes, clusters, _, _ := envoy.CreateRoutesWithClusters(adapterInternalAPI, nil, "prod.gw.wso2.com", "carbon.super")
assert.Equal(t, 3, len(clusters), "Number of production clusters created is incorrect.")

orderServiceCluster := clusters[1]
@@ -483,9 +483,9 @@ func TestCreateRoutesWithClustersWithBackendTLSConfigs(t *testing.T) {
xds.SanitizeGateway("default-gateway", true)

adapterInternalAPI, labels, err := synchronizer.GenerateAdapterInternalAPI(apiState, &httpRouteState, constants.Production)
assert.Equal(t, map[string]struct{}{"default-gateway": struct{}{}}, labels, "Labels are incorrect.")
assert.Equal(t, map[string]struct{}{"default-gateway": {}}, labels, "Labels are incorrect.")
assert.Nil(t, err, "Error should not be present when apiState is converted to a AdapterInternalAPI object")
_, clusters, _, _ := envoy.CreateRoutesWithClusters(*adapterInternalAPI, nil, "prod.gw.wso2.com", "carbon.super")
_, clusters, _, _ := envoy.CreateRoutesWithClusters(adapterInternalAPI, nil, "prod.gw.wso2.com", "carbon.super")
assert.Equal(t, 2, len(clusters), "Number of production clusters created is incorrect.")

exactPathCluster := clusters[1]
@@ -811,9 +811,9 @@ func TestCreateRoutesWithClustersDifferentBackendRefs(t *testing.T) {
xds.SanitizeGateway("default-gateway", true)

adapterInternalAPI, labels, err := synchronizer.GenerateAdapterInternalAPI(apiState, &httpRouteState, constants.Production)
assert.Equal(t, map[string]struct{}{"default-gateway": struct{}{}}, labels, "Labels are incorrect.")
assert.Equal(t, map[string]struct{}{"default-gateway": {}}, labels, "Labels are incorrect.")
assert.Nil(t, err, "Error should not be present when apiState is converted to a AdapterInternalAPI object")
_, clusters, _, _ := envoy.CreateRoutesWithClusters(*adapterInternalAPI, nil, "prod.gw.wso2.com", "carbon.super")
_, clusters, _, _ := envoy.CreateRoutesWithClusters(adapterInternalAPI, nil, "prod.gw.wso2.com", "carbon.super")
assert.Equal(t, 3, len(clusters), "Number of production clusters created is incorrect.")
}

@@ -897,8 +897,8 @@ func TestCreateRoutesWithClustersSameBackendRefs(t *testing.T) {
xds.SanitizeGateway("default-gateway", true)

adapterInternalAPI, labels, err := synchronizer.GenerateAdapterInternalAPI(apiState, &httpRouteState, constants.Production)
assert.Equal(t, map[string]struct{}{"default-gateway": struct{}{}}, labels, "Labels are incorrect.")
assert.Equal(t, map[string]struct{}{"default-gateway": {}}, labels, "Labels are incorrect.")
assert.Nil(t, err, "Error should not be present when apiState is converted to a AdapterInternalAPI object")
_, clusters, _, _ := envoy.CreateRoutesWithClusters(*adapterInternalAPI, nil, "prod.gw.wso2.com", "carbon.super")
_, clusters, _, _ := envoy.CreateRoutesWithClusters(adapterInternalAPI, nil, "prod.gw.wso2.com", "carbon.super")
assert.Equal(t, 2, len(clusters), "Number of production clusters created is incorrect.")
}

0 comments on commit 023c1b6

Please sign in to comment.