subtranslator

package
v3.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 2, 2025 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// FromResourceKindPriorityShiftBits is the highest 2 bits 45-44 used in priority field of Kong route
	// to note the kind of the resource from which the route is translated.
	// 11 - routes from Ingress.
	// 10 - routes from HTTPRoute.
	// 01 - routes from GRPCRoute.
	FromResourceKindPriorityShiftBits = 44
	// ResourceKindBitsIngress is the value of highest 2 bits for routes from ingresses.
	ResourceKindBitsIngress = 3
	// ResourceKindBitsHTTPRoute is the value of highest 2 bits for routes from HTTPRoutes.
	ResourceKindBitsHTTPRoute = 2
	// ResourceKindBitsGRPCRoute is the value of highest 2 bits for routes from GRPCRoutes.
	ResourceKindBitsGRPCRoute = 1
)
View Source
const (
	// KongPathRegexPrefix is the reserved prefix string that instructs Kong 3.0+ to interpret a path as a regex.
	KongPathRegexPrefix = "~"

	// KongHeaderRegexPrefix is a reserved prefix string that Kong uses to determine if it should parse a header value
	// as a regex.
	KongHeaderRegexPrefix = "~*"

	// ControllerPathRegexPrefix is the prefix string used to indicate that the controller should treat a path as a
	// regular expression. The controller replaces this prefix with KongPathRegexPrefix when sending routes to Kong.
	ControllerPathRegexPrefix = "/~"

	// DefaultServiceTimeout indicates the amount of time (by default) for
	// connections, reads and writes to a service over a network should
	// be given before timing out by default.
	DefaultServiceTimeout = 60000

	// DefaultRetries indicates the number of times a connection should be
	// retried by default.
	DefaultRetries = 5

	// DefualtKongServiceProtocol is the default protocol in translated Kong service.
	DefualtKongServiceProtocol = "http"
)
View Source
const (
	// CatchAllHTTPExpression is the expression to match all HTTP/HTTPS requests.
	// For rules with no matches and no hostnames in its parent HTTPRoute or GRPCRoute,
	// we need to generate a "catch-all" route for the rule:
	// https://github.com/Kong/kubernetes-ingress-controller/issues/4526
	// but Kong does not allow empty expression in expression router,
	// so we define this is we need a route to match all HTTP/HTTPS requests.
	CatchAllHTTPExpression = `(net.protocol == "http") || (net.protocol == "https")`
)

Variables

View Source
var (
	ErrRouteValidationNoRules                          = errors.New("no rules provided")
	ErrRouteValidationQueryParamMatchesUnsupported     = errors.New("query param matches are not yet supported")
	ErrRouteValidationNoMatchRulesOrHostnamesSpecified = errors.New("no match rules or hostnames specified")
	ErrRotueValidationRuleNoBackendRef                 = errors.New("no backendRefs in rule")
)

Functions

func ApplyExpressionToL4KongRoute

func ApplyExpressionToL4KongRoute(r *kongstate.Route)

ApplyExpressionToL4KongRoute convert route flavor from traditional to expressions against protocols, snis and dest ports.

func GenerateKongExpressionRoutesFromGRPCRouteRule

func GenerateKongExpressionRoutesFromGRPCRouteRule(grpcroute *gatewayapi.GRPCRoute, ruleNumber int) []kongstate.Route

GenerateKongExpressionRoutesFromGRPCRouteRule generates expression based kong routes from a single GRPCRouteRule.

func GenerateKongExpressionRoutesFromHTTPRouteMatches

func GenerateKongExpressionRoutesFromHTTPRouteMatches(
	translation KongRouteTranslation,
	ingressObjectInfo util.K8sObjectInfo,
	hostnames []string,
	tags []*string,
	supportRedirectPlugin bool,
) ([]kongstate.Route, error)

GenerateKongExpressionRoutesFromHTTPRouteMatches generates Kong routes from HTTPRouteRule pointing to a specific backend.

func GenerateKongRoutesFromGRPCRouteRule

func GenerateKongRoutesFromGRPCRouteRule(
	grpcroute *gatewayapi.GRPCRoute,
	ruleNumber int,
	storer store.Storer,
) []kongstate.Route

func GenerateKongRoutesFromHTTPRouteMatches added in v3.4.0

func GenerateKongRoutesFromHTTPRouteMatches(
	routeName string,
	matches []gatewayapi.HTTPRouteMatch,
	filters []gatewayapi.HTTPRouteFilter,
	ingressObjectInfo util.K8sObjectInfo,
	hostnames []*string,
	tags []*string,
	options TranslateHTTPRouteRulesToKongRouteOptions,
) ([]kongstate.Route, error)

GenerateKongRoutesFromHTTPRouteMatches converts an HTTPRouteMatches to a slice of Kong Route objects with traditional routes. This function assumes that the HTTPRouteMatches share the query params, headers and methods.

func IsKongServiceFacade

func IsKongServiceFacade(resource *corev1.TypedLocalObjectReference) bool

IsKongServiceFacade returns true if the given resource reference is a KongServiceFacade.

func KongExpressionRouteFromSplitGRPCRouteMatchWithPriority

func KongExpressionRouteFromSplitGRPCRouteMatchWithPriority(
	matchWithPriority SplitGRPCRouteMatchToPriority,
) kongstate.Route

KongExpressionRouteFromSplitGRPCRouteMatchWithPriority generates expression based Kong route from split GRPCRoute match which contains one or no hostname, and a GRPCRoute match, with its priority is beforehand.

func KongServiceNameFromSplitGRPCRouteMatch

func KongServiceNameFromSplitGRPCRouteMatch(match SplitGRPCRouteMatch) string

KongServiceNameFromSplitGRPCRouteMatch generates the name of translated Kong service from split GRPCRoute match with the source GRPCRoute and rule index.

func MaybePrependRegexPrefix

func MaybePrependRegexPrefix(path, controllerPrefix string, applyLegacyHeuristic bool) string

MaybePrependRegexPrefix takes a path, controller regex prefix, and a legacy heuristic toggle. It returns the path with the Kong regex path prefix if it either began with the controller prefix or did not, but matched the legacy heuristic, and the heuristic was enabled.

func MaybePrependRegexPrefixForIngressV1Fn

func MaybePrependRegexPrefixForIngressV1Fn(ingress *netv1.Ingress, applyLegacyHeuristic bool) func(path string) *string

MaybePrependRegexPrefixForIngressV1Fn returns a function that prepends a regex prefix to a path for a given netv1.Ingress.

func MaybeRewriteURI

func MaybeRewriteURI(service *kongstate.Service, rewriteURIEnable bool) error

MaybeRewriteURI appends a request-transformer plugin to Kong routes based on the value of konghq.com/rewrite annotation configured on related K8s Ingresses.

func PathsFromIngressPaths

func PathsFromIngressPaths(httpIngressPath netv1.HTTPIngressPath) []*string

PathsFromIngressPaths takes a path and Ingress path type and returns a set of Kong route paths that satisfy that path type. It optionally adds the Kong 3.x regex path prefix for path types that require a regex path. It rejects unknown path types with an error.

func PortDefFromPortNumber

func PortDefFromPortNumber(port int32) kongstate.PortDef

func PortDefFromServiceBackendPort

func PortDefFromServiceBackendPort(sbp *netv1.ServiceBackendPort) kongstate.PortDef

func TranslateIngresses

func TranslateIngresses(
	ingresses []*netv1.Ingress,
	icp kongv1alpha1.IngressClassParametersSpec,
	flags TranslateIngressFeatureFlags,
	translatedObjectsCollector TranslatedKubernetesObjectsCollector,
	failuresCollector FailuresCollector,
	storer store.Storer,
) map[string]kongstate.Service

TranslateIngresses receives a slice of Kubernetes Ingress objects and produces a translated set of kong.Services and kong.Routes which will come wrapped in a kongstate.Service object.

Types

type FailuresCollector

type FailuresCollector interface {
	PushResourceFailure(reason string, causingObjects ...client.Object)
}

FailuresCollector is an interface for collecting failures during translation.

type GRPCRoutePriorityTraits

type GRPCRoutePriorityTraits struct {
	// PreciseHostname is set to true if the hostname is non-wildcard.
	PreciseHostname bool
	// HostnameLength is the length of hostname. Max 253.
	HostnameLength int
	// MethodMatchType is the type of method match (if exists).
	// preserve this field since the API specification has not provided priority of type of method match yet.
	// (In normal situation should be higher than length of service/method value).
	// related issue: https://github.com/kubernetes-sigs/gateway-api/issues/2216
	MethodMatchType gatewayapi.GRPCMethodMatchType
	// ServiceLength is the length of GRPC service name. Max 1024.
	ServiceLength int
	// MethodLength is the length of GRPC method name. Max 1024.
	MethodLength int
	// HeaderCount is the number of header matches in the match. Max 16.
	HeaderCount int
}

func CalculateGRCPRouteMatchPriorityTraits

func CalculateGRCPRouteMatchPriorityTraits(match SplitGRPCRouteMatch) GRPCRoutePriorityTraits

CalculateGRCPRouteMatchPriorityTraits calculates the traits to decide priority based on the hostname and match split from source GRPCRoute. Specification of priority goes as follow: (The following comments are extracted from gateway API specification about GRPCRoute)

Precedence MUST be given to the rule with the largest number of:

  • Characters in a matching non-wildcard hostname.
  • Characters in a matching hostname.
  • Characters in a matching service.
  • Characters in a matching method.
  • Header matches.

Method match type is preserved since the specification of GRPCRoute has not provided its priority yet.

func (GRPCRoutePriorityTraits) EncodeToPriority

func (t GRPCRoutePriorityTraits) EncodeToPriority() RoutePriorityType

EncodeToPriority turns GRPCRoute priority traits into the integer expressed priority.

	   4                   3                   2                   1
 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
+-+---------------+---------------------+---------------------+---------+----------------+
|P| host len      | GRPC service length | GRPC method length  |Header No| relative order |
+-+---------------+---------------------+---------------------+---------+----------------+

Where: P: set to 1 if the hostname is non-wildcard. host len: length of hostname. GRPC service length: length of `Service` part in method match GRPC method length: length of `Method` part in method match Header No.: number of header matches. relative order: relative order of creation timestamp, namespace and name and internal rule/match order between different (split) GRPCRoutes.

REVIEW: althogh not specified in official docs, do we need to assign a bit for GRPC method match type to assign higher priority for method match with `Exact` match?

type HTTPRoutePriorityTraits

type HTTPRoutePriorityTraits struct {
	PreciseHostname bool
	HostnameLength  int
	PathType        gatewayapi.PathMatchType
	PathLength      int
	HeaderCount     int
	HasMethodMatch  bool
	QueryParamCount int
}

func CalculateHTTPRouteMatchPriorityTraits

func CalculateHTTPRouteMatchPriorityTraits(match SplitHTTPRouteMatch) HTTPRoutePriorityTraits

CalculateHTTPRouteMatchPriorityTraits calculates the parts of priority that can be decided by the fields in spec of the match split from HTTPRoute. Specification of priority goes as follow: (The following comments are extracted from gateway API specification about HTTPRoute)

In the event that multiple HTTPRoutes specify intersecting hostnames, precedence must be given to rules from the HTTPRoute with the largest number of:

  • Characters in a matching non-wildcard hostname.
  • Characters in a matching hostname.

If ties exist across multiple Routes, the matching precedence rules for HTTPRouteMatches takes over.

Proxy or Load Balancer routing configuration generated from HTTPRoutes MUST prioritize matches based on the following criteria, continuing on ties. Across all rules specified on applicable Routes, precedence must be given to the match having:

  • "Exact” path match.
  • "Prefix" path match with largest number of characters.
  • Method match.
  • Largest number of header matches.
  • Largest number of query param matches.

func (HTTPRoutePriorityTraits) EncodeToPriority

func (t HTTPRoutePriorityTraits) EncodeToPriority() RoutePriorityType

EncodeToPriority turns HTTPRoute priority traits into the integer expressed priority.

	   4                   3                   2                   1
 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
+-+---------------+-+-+-------------------+-+---------+---------+-----------------------+
|P| host len      |E|R|  Path length      |M|Header No|Query No.| relative order        |
+-+---------------+-+-+-------------------+-+---------+-------- +-----------------------+

Where: P: set to 1 if the hostname is non-wildcard. host len: host length of hostname. E: set to 1 if the path type is `Exact`. R: set to 1 if the path type in `RegularExpression`. Path length: length of `path.Value`. M: set to 1 if Method match is specified. Header No.: number of header matches. Query No.: number of query parameter matches. relative order: relative order of creation timestamp, namespace and name and internal rule/match order between different (split) HTTPRoutes.

type HTTPRouteRuleCacheByServiceName added in v3.4.0

type HTTPRouteRuleCacheByServiceName struct {
	// contains filtered or unexported fields
}

HTTPRouteRuleCacheByServiceName is the cache to store HTTP rules that are translated to the same Kong gateway service grouped by the name of the Kong gateway service.

type HTTPRoutesTranslationResult added in v3.4.0

type HTTPRoutesTranslationResult struct {
	ServiceNameToKongstateService    map[string]kongstate.Service
	HTTPRouteNameToTranslationErrors map[k8stypes.NamespacedName][]error
}

HTTPRoutesTranslationResult is the result of translating HTTPRoutes to Kong gateway services. It includes the kongstate services indexed by the Kong gateway service name and translation errors happened on each HTTPRoute to genereate TranslationFailure events.

func TranslateHTTPRoutesToKongstateServices added in v3.4.0

func TranslateHTTPRoutesToKongstateServices(
	logger logr.Logger,
	storer store.Storer,
	routes []*gatewayapi.HTTPRoute,
	options TranslateHTTPRouteToKongstateServiceOptions,
) HTTPRoutesTranslationResult

TranslateHTTPRoutesToKongstateServices translates a set of HTTPRoutes to kongstate services, and collect the translation errors in the process of translating.

type Header string

Header represents a header as a string "key:value" or just "key". This is the format accepted by TransformerPluginConfig.

func NewHeader added in v3.4.0

func NewHeader(key, value string) Header

NewHeader creates a new Header with the given key and value in format accepted by TransformerPluginConfig. For key-only header (e.g. for remove filter), set value to an empty string.

type IngressRoutePriorityTraits

type IngressRoutePriorityTraits struct {
	MatchFields   int
	PlainHostOnly bool
	HeaderCount   int
	MaxPathLength int
	HasRegexPath  bool
}

func (IngressRoutePriorityTraits) EncodeToPriority

func (t IngressRoutePriorityTraits) EncodeToPriority() RoutePriorityType

EncodeToPriority encodes the traits to `priority` field used in Kong expression based routes. The bits are assigned in the following way:

      4                   3                   2                   1
3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0

+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | MF | Header Number |P| PRESERVED |R| Path Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

Where:

  • MF (Match Fields): how many fields there are to match on (path, host, headers, methods, SNIs).
  • Header Number: number of headers to match.
  • PRESERVED: reserved for future use if we want add other fields into consideration.
  • P (Plain Host): set if ALL hosts are non-wildcard.
  • R (Regex): if set, regex match is used.
  • Path Length: maximum length of the path to match.

type KongRouteTranslation

type KongRouteTranslation struct {
	Name string
	// OptionalNamedRouteRules represents list of RouteName - an optional name
	// of the particular route that can be defined in the K8s HTTPRoute,
	// https://gateway-api.sigs.k8s.io/geps/gep-995/#api.
	OptionalNamedRouteRules []string
	Matches                 []gatewayapi.HTTPRouteMatch
	Filters                 []gatewayapi.HTTPRouteFilter
}

KongRouteTranslation is a translation of a single HTTPRoute rule into metadata that can be used to instantiate Kong routes.

type KongServiceTranslation

type KongServiceTranslation struct {
	Name        string
	BackendRefs []gatewayapi.HTTPBackendRef
	KongRoutes  []KongRouteTranslation
}

KongServiceTranslation is a translation of a single HTTPRoute into metadata that can be used to instantiate Kong routes and services. Routes from this object should route traffic to BackendRefs from this object.

type RoutePriorityType

type RoutePriorityType = uint64

RoutePriorityType is the type of priority field of Kong routes.

const IngressDefaultBackendPriority RoutePriorityType = 0

type SplitGRPCRouteMatch

type SplitGRPCRouteMatch struct {
	Source     *gatewayapi.GRPCRoute
	Hostname   string
	Match      gatewayapi.GRPCRouteMatch
	RuleIndex  int
	MatchIndex int
}

SplitGRPCRouteMatch is the GRPCRouteMatch split by rule and match from the source GRPCRoute. RuleIndex and MatchIndex annotates the place of the match in the source GRPCRoute.

func SplitGRPCRoute

func SplitGRPCRoute(grpcroute *gatewayapi.GRPCRoute) []SplitGRPCRouteMatch

SplitGRPCRoute splits a GRPCRoute by hostname and match into multiple matches. Each split match contains at most 1 hostname, and 1 rule with 1 match.

type SplitGRPCRouteMatchToPriority

type SplitGRPCRouteMatchToPriority struct {
	Match    SplitGRPCRouteMatch
	Priority uint64
}

func AssignRoutePriorityToSplitGRPCRouteMatches

func AssignRoutePriorityToSplitGRPCRouteMatches(
	logger logr.Logger,
	splitGRPCouteMatches []SplitGRPCRouteMatch,
) []SplitGRPCRouteMatchToPriority

AssignRoutePriorityToSplitGRPCRouteMatches assigns priority to ALL split GRPCRoute matches that are split by hostnames and matches from GRPCRoutes listed from the cache. Firstly assign "fixed" bits by the following fields of the matches: hostname, GRPC method match, number of header matches. If ties exists in the first step, where multiple matches has the same priority calculated from the fields, we run a sort for the matches in the tie and assign the bits for "relative order" according to the sorting result of these matches.

type SplitHTTPRouteMatch

type SplitHTTPRouteMatch struct {
	Source   *gatewayapi.HTTPRoute
	Hostname string
	Match    gatewayapi.HTTPRouteMatch
	// OptionalNamedRouteRule represents RouteName - an optional name
	// of the particular route that can be defined in the K8s HTTPRoute,
	// https://gateway-api.sigs.k8s.io/geps/gep-995/#api.
	OptionalNamedRouteRule string
	RuleIndex              int
	MatchIndex             int
}

func SplitHTTPRoute

func SplitHTTPRoute(httproute *gatewayapi.HTTPRoute) []SplitHTTPRouteMatch

SplitHTTPRoute splits HTTPRoutes into matches with at most one hostname, and one rule with exactly one match. It will split one rule with multiple hostnames and multiple matches to one hostname and one match per each HTTPRoute.

type SplitHTTPRouteMatchToKongRoutePriority

type SplitHTTPRouteMatchToKongRoutePriority struct {
	Match    SplitHTTPRouteMatch
	Priority RoutePriorityType
}

type TransformerPluginConfig added in v3.2.0

type TransformerPluginConfig struct {
	Headers []Header `json:"headers,omitempty"`
}

TransformerPluginConfig is a configuration for request-transformer and response-transformer plugins' "add", "append", and "remove" fields.

type TransformerPluginReplaceConfig added in v3.2.0

type TransformerPluginReplaceConfig struct {
	Headers []Header `json:"headers,omitempty"`
	URI     string   `json:"uri,omitempty"`
}

TransformerPluginReplaceConfig is a configuration for request-transformer and response-transformer plugins' "replace" field.

type TranslateHTTPRouteRulesToKongRouteOptions added in v3.4.0

type TranslateHTTPRouteRulesToKongRouteOptions struct {
	ExpressionRoutes      bool
	SupportRedirectPlugin bool
}

type TranslateHTTPRouteToKongstateServiceOptions added in v3.4.0

type TranslateHTTPRouteToKongstateServiceOptions struct {
	CombinedServicesFromDifferentHTTPRoutes bool
	ExpressionRoutes                        bool
	SupportRedirectPlugin                   bool
}

TranslateHTTPRouteToKongstateServiceOptions is the set of options to translate HTTPRoutes to kongstate services.

type TranslateIngressFeatureFlags

type TranslateIngressFeatureFlags struct {
	// ExpressionRoutes indicates whether to translate Kubernetes objects to expression based Kong Routes.
	ExpressionRoutes bool

	// KongServiceFacade indicates whether we should support KongServiceFacade as Ingress backends.
	KongServiceFacade bool
}

type TranslatedKubernetesObjectsCollector

type TranslatedKubernetesObjectsCollector interface {
	Add(client.Object)
}

TranslatedKubernetesObjectsCollector is an interface for collecting Kubernetes objects that have been translated successfully.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL