subtranslator

package
v3.1.4 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2024 License: Apache-2.0 Imports: 25 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 = "~"

	// 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 = "/~"
)
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,
) ([]kongstate.Route, error)

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

func GenerateKongRoutesFromGRPCRouteRule

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

func IsKongServiceFacade

func IsKongServiceFacade(resource *corev1.TypedLocalObjectReference) bool

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

func KongExpressionRouteFromHTTPRouteMatchWithPriority

func KongExpressionRouteFromHTTPRouteMatchWithPriority(
	httpRouteMatchWithPriority SplitHTTPRouteMatchToKongRoutePriority,
) (*kongstate.Route, error)

KongExpressionRouteFromHTTPRouteMatchWithPriority translates a split HTTPRoute match into expression based kong route with assigned priority.

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 KongServiceNameFromSplitHTTPRouteMatch

func KongServiceNameFromSplitHTTPRouteMatch(match SplitHTTPRouteMatch) string

KongServiceNameFromSplitHTTPRouteMatch generates service name from split HTTPRoute match. since one HTTPRoute may be split by hostname and rule, the service name will be generated in the format "httproute.<namespace>.<name>.<hostname>.<rule index>". For example: `httproute.default.example.foo.com.0`.

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 SetRoutePlugins

func SetRoutePlugins(route *kongstate.Route, filters []gatewayapi.HTTPRouteFilter, path string, tags []*string) error

SetRoutePlugins converts HTTPRouteFilter into Kong plugins. The plugins are set into the given kongstate.Route. The plugins can be set in two different ways: - Direct conversion from the respective HTTPRouteFilter. - ExtensionRef to plugins annotation from the ExtensionRef filter.

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

func TranslateHTTPRoute

func TranslateHTTPRoute(route *gatewayapi.HTTPRoute) []*KongServiceTranslation

TranslateHTTPRoute translates a list of HTTPRoutes into a list of HTTPRouteTranslationMeta objects that can be used to instantiate Kong routes and services. The translation is done by grouping the HTTPRoutes by their backendRefs. This means that all the rules of a single HTTPRoute will be grouped together if they share the same backendRefs.

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

func AssignRoutePriorityToSplitHTTPRouteMatches

func AssignRoutePriorityToSplitHTTPRouteMatches(
	logger logr.Logger,
	splitHTTPRouteMatches []SplitHTTPRouteMatch,
) []SplitHTTPRouteMatchToKongRoutePriority

AssignRoutePriorityToSplitHTTPRouteMatches assigns priority to ALL split matches from ALL HTTPRoutes in the cache. Firstly assign "fixed" bits by the following fields of the match: hostname, path type, path length, method match, number of header matches, number of query param 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 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