xdsresource

package
v0.0.0-...-7d1ee88 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2023 License: Apache-2.0 Imports: 41 Imported by: 0

Documentation

Overview

Package xdsresource implements the xDS data model layer.

Provides resource-type specific functionality to unmarshal xDS protos into internal data structures that contain only fields gRPC is interested in. These internal data structures are passed to components in the xDS stack (resolver/balancers/server) that have expressed interest in receiving updates to specific resources.

Index

Constants

View Source
const FederationScheme = "xdstp"

FederationScheme is the scheme of a federation resource name.

Variables

View Source
var RandInt63n = grpcrand.Int63n

RandInt63n overwrites grpcrand for control in tests.

Functions

func IsClusterResource

func IsClusterResource(url string) bool

IsClusterResource returns true if the provider URL corresponds to an xDS Cluster resource.

func IsEndpointsResource

func IsEndpointsResource(url string) bool

IsEndpointsResource returns true if the provider URL corresponds to an xDS Endpoints resource.

func IsHTTPConnManagerResource

func IsHTTPConnManagerResource(url string) bool

IsHTTPConnManagerResource returns true if the provider URL corresponds to an xDS HTTPConnManager resource.

func IsListenerResource

func IsListenerResource(url string) bool

IsListenerResource returns true if the provider URL corresponds to an xDS Listener resource.

func IsRouteConfigResource

func IsRouteConfigResource(url string) bool

IsRouteConfigResource returns true if the provider URL corresponds to an xDS RouteConfig resource.

func NewErrorf

func NewErrorf(t ErrorType, format string, args ...interface{}) error

NewErrorf creates an xds client error. The callbacks are called with this error, to pass additional information about the error.

func WatchCluster

func WatchCluster(p Producer, name string, w ClusterWatcher) (cancel func())

WatchCluster uses xDS to discover the configuration associated with the provided cluster resource name.

func WatchEndpoints

func WatchEndpoints(p Producer, name string, w EndpointsWatcher) (cancel func())

WatchEndpoints uses xDS to discover the configuration associated with the provided endpoints resource name.

func WatchListener

func WatchListener(p Producer, name string, w ListenerWatcher) (cancel func())

WatchListener uses xDS to discover the configuration associated with the provided listener resource name.

func WatchRouteConfig

func WatchRouteConfig(p Producer, name string, w RouteConfigWatcher) (cancel func())

WatchRouteConfig uses xDS to discover the configuration associated with the provided route configuration resource name.

Types

type ClusterLBPolicyRingHash

type ClusterLBPolicyRingHash struct {
	MinimumRingSize uint64
	MaximumRingSize uint64
}

ClusterLBPolicyRingHash represents ring_hash lb policy, and also contains its config.

type ClusterLRSServerConfigType

type ClusterLRSServerConfigType int

ClusterLRSServerConfigType is the type of LRS server config.

const (
	// ClusterLRSOff indicates LRS is off (loads are not reported for this
	// cluster).
	ClusterLRSOff ClusterLRSServerConfigType = iota
	// ClusterLRSServerSelf indicates loads should be reported to the same
	// server (the authority) where the CDS resp is received from.
	ClusterLRSServerSelf
)

type ClusterResourceData

type ClusterResourceData struct {
	ResourceData

	// TODO: We have always stored update structs by value. See if this can be
	// switched to a pointer?
	Resource ClusterUpdate
}

ClusterResourceData wraps the configuration of a Cluster resource as received from the management server.

Implements the ResourceData interface.

func (*ClusterResourceData) Equal

func (c *ClusterResourceData) Equal(other ResourceData) bool

Equal returns true if other is equal to r.

func (*ClusterResourceData) Raw

func (c *ClusterResourceData) Raw() *anypb.Any

Raw returns the underlying raw protobuf form of the cluster resource.

func (*ClusterResourceData) ToJSON

func (c *ClusterResourceData) ToJSON() string

ToJSON returns a JSON string representation of the resource data.

type ClusterType

type ClusterType int

ClusterType is the type of cluster from a received CDS response.

const (
	// ClusterTypeEDS represents the EDS cluster type, which will delegate endpoint
	// discovery to the management server.
	ClusterTypeEDS ClusterType = iota
	// ClusterTypeLogicalDNS represents the Logical DNS cluster type, which essentially
	// maps to the gRPC behavior of using the DNS resolver with pick_first LB policy.
	ClusterTypeLogicalDNS
	// ClusterTypeAggregate represents the Aggregate Cluster type, which provides a
	// prioritized list of clusters to use. It is used for failover between clusters
	// with a different configuration.
	ClusterTypeAggregate
)

type ClusterUpdate

type ClusterUpdate struct {
	ClusterType ClusterType
	// ClusterName is the clusterName being watched for through CDS.
	ClusterName string
	// EDSServiceName is an optional name for EDS. If it's not set, the balancer
	// should watch ClusterName for the EDS resources.
	EDSServiceName string
	// LRSServerConfig contains the server where the load reports should be sent
	// to. This can be change to an interface, to support other types, e.g. a
	// ServerConfig with ServerURI, creds.
	LRSServerConfig ClusterLRSServerConfigType
	// SecurityCfg contains security configuration sent by the control plane.
	SecurityCfg *SecurityConfig
	// MaxRequests for circuit breaking, if any (otherwise nil).
	MaxRequests *uint32
	// DNSHostName is used only for cluster type DNS. It's the DNS name to
	// resolve in "host:port" form
	DNSHostName string
	// PrioritizedClusterNames is used only for cluster type aggregate. It represents
	// a prioritized list of cluster names.
	PrioritizedClusterNames []string

	// LBPolicy is the lb policy for this cluster.
	//
	// This only support round_robin and ring_hash.
	// - if it's nil, the lb policy is round_robin
	// - if it's not nil, the lb policy is ring_hash, the this field has the config.
	//
	// When we add more support policies, this can be made an interface, and
	// will be set to different types based on the policy type.
	LBPolicy *ClusterLBPolicyRingHash

	// OutlierDetection is the outlier detection configuration for this cluster.
	// If nil, it means this cluster does not use the outlier detection feature.
	OutlierDetection *OutlierDetection

	// Raw is the resource from the xds response.
	Raw *anypb.Any
}

ClusterUpdate contains information from a received CDS response, which is of interest to the registered CDS watcher.

type ClusterUpdateErrTuple

type ClusterUpdateErrTuple struct {
	Update ClusterUpdate
	Err    error
}

ClusterUpdateErrTuple is a tuple with the update and error. It contains the results from unmarshal functions. It's used to pass unmarshal results of multiple resources together, e.g. in maps like `map[string]{Update,error}`.

type ClusterWatcher

type ClusterWatcher interface {
	// OnUpdate is invoked to report an update for the resource being watched.
	OnUpdate(*ClusterResourceData)

	// OnError is invoked under different error conditions including but not
	// limited to the following:
	//	- authority mentioned in the resource is not found
	//	- resource name parsing error
	//	- resource deserialization error
	//	- resource validation error
	//	- ADS stream failure
	//	- connection failure
	OnError(error)

	// OnResourceDoesNotExist is invoked for a specific error condition where
	// the requested resource is not found on the xDS management server.
	OnResourceDoesNotExist()
}

ClusterWatcher wraps the callbacks to be invoked for different events corresponding to the cluster resource being watched.

type CompositeMatcher

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

CompositeMatcher is a matcher that holds onto many matchers and aggregates the matching results.

func RouteToMatcher

func RouteToMatcher(r *Route) (*CompositeMatcher, error)

RouteToMatcher converts a route to a Matcher to match incoming RPC's against.

func (*CompositeMatcher) Match

func (a *CompositeMatcher) Match(info iresolver.RPCInfo) bool

Match returns true if all matchers return true.

func (*CompositeMatcher) String

func (a *CompositeMatcher) String() string

type DecodeOptions

type DecodeOptions struct {
	// BootstrapConfig contains the bootstrap configuration passed to the
	// top-level xdsClient. This contains useful data for resource validation.
	BootstrapConfig *bootstrap.Config
}

DecodeOptions wraps the options required by ResourceType implementation for decoding configuration received from the xDS management server.

type DecodeResult

type DecodeResult struct {
	// Name is the name of the resource being watched.
	Name string
	// Resource contains the configuration associated with the resource being
	// watched.
	Resource ResourceData
}

DecodeResult is the result of a decode operation.

type Endpoint

type Endpoint struct {
	Address      string
	HealthStatus EndpointHealthStatus
	Weight       uint32
}

Endpoint contains information of an endpoint.

type EndpointHealthStatus

type EndpointHealthStatus int32

EndpointHealthStatus represents the health status of an endpoint.

const (
	// EndpointHealthStatusUnknown represents HealthStatus UNKNOWN.
	EndpointHealthStatusUnknown EndpointHealthStatus = iota
	// EndpointHealthStatusHealthy represents HealthStatus HEALTHY.
	EndpointHealthStatusHealthy
	// EndpointHealthStatusUnhealthy represents HealthStatus UNHEALTHY.
	EndpointHealthStatusUnhealthy
	// EndpointHealthStatusDraining represents HealthStatus DRAINING.
	EndpointHealthStatusDraining
	// EndpointHealthStatusTimeout represents HealthStatus TIMEOUT.
	EndpointHealthStatusTimeout
	// EndpointHealthStatusDegraded represents HealthStatus DEGRADED.
	EndpointHealthStatusDegraded
)

type EndpointsResourceData

type EndpointsResourceData struct {
	ResourceData

	// TODO: We have always stored update structs by value. See if this can be
	// switched to a pointer?
	Resource EndpointsUpdate
}

EndpointsResourceData wraps the configuration of an Endpoints resource as received from the management server.

Implements the ResourceData interface.

func (*EndpointsResourceData) Equal

func (e *EndpointsResourceData) Equal(other ResourceData) bool

Equal returns true if other is equal to r.

func (*EndpointsResourceData) Raw

func (e *EndpointsResourceData) Raw() *anypb.Any

Raw returns the underlying raw protobuf form of the listener resource.

func (*EndpointsResourceData) ToJSON

func (e *EndpointsResourceData) ToJSON() string

ToJSON returns a JSON string representation of the resource data.

type EndpointsUpdate

type EndpointsUpdate struct {
	Drops []OverloadDropConfig
	// Localities in the EDS response with `load_balancing_weight` field not set
	// or explicitly set to 0 are ignored while parsing the resource, and
	// therefore do not show up here.
	Localities []Locality

	// Raw is the resource from the xds response.
	Raw *anypb.Any
}

EndpointsUpdate contains an EDS update.

type EndpointsUpdateErrTuple

type EndpointsUpdateErrTuple struct {
	Update EndpointsUpdate
	Err    error
}

EndpointsUpdateErrTuple is a tuple with the update and error. It contains the results from unmarshal functions. It's used to pass unmarshal results of multiple resources together, e.g. in maps like `map[string]{Update,error}`.

type EndpointsWatcher

type EndpointsWatcher interface {
	// OnUpdate is invoked to report an update for the resource being watched.
	OnUpdate(*EndpointsResourceData)

	// OnError is invoked under different error conditions including but not
	// limited to the following:
	//	- authority mentioned in the resource is not found
	//	- resource name parsing error
	//	- resource deserialization error
	//	- resource validation error
	//	- ADS stream failure
	//	- connection failure
	OnError(error)

	// OnResourceDoesNotExist is invoked for a specific error condition where
	// the requested resource is not found on the xDS management server.
	OnResourceDoesNotExist()
}

EndpointsWatcher wraps the callbacks to be invoked for different events corresponding to the endpoints resource being watched.

type ErrorType

type ErrorType int

ErrorType is the type of the error that the watcher will receive from the xds client.

const (
	// ErrorTypeUnknown indicates the error doesn't have a specific type. It is
	// the default value, and is returned if the error is not an xds error.
	ErrorTypeUnknown ErrorType = iota
	// ErrorTypeConnection indicates a connection error from the gRPC client.
	ErrorTypeConnection
	// ErrorTypeResourceNotFound indicates a resource is not found from the xds
	// response. It's typically returned if the resource is removed in the xds
	// server.
	ErrorTypeResourceNotFound
	// ErrorTypeResourceTypeUnsupported indicates the receipt of a message from
	// the management server with resources of an unsupported resource type.
	ErrorTypeResourceTypeUnsupported
)

func ErrType

func ErrType(e error) ErrorType

ErrType returns the error's type.

type FilterChain

type FilterChain struct {
	// SecurityCfg contains transport socket security configuration.
	SecurityCfg *SecurityConfig
	// HTTPFilters represent the HTTP Filters that comprise this FilterChain.
	HTTPFilters []HTTPFilter
	// RouteConfigName is the route configuration name for this FilterChain.
	//
	// Exactly one of RouteConfigName and InlineRouteConfig is set.
	RouteConfigName string
	// InlineRouteConfig is the inline route configuration (RDS response)
	// returned for this filter chain.
	//
	// Exactly one of RouteConfigName and InlineRouteConfig is set.
	InlineRouteConfig *RouteConfigUpdate
}

FilterChain captures information from within a FilterChain message in a Listener resource.

func (*FilterChain) ConstructUsableRouteConfiguration

func (f *FilterChain) ConstructUsableRouteConfiguration(config RouteConfigUpdate) ([]VirtualHostWithInterceptors, error)

ConstructUsableRouteConfiguration takes Route Configuration and converts it into matchable route configuration, with instantiated HTTP Filters per route.

type FilterChainLookupParams

type FilterChainLookupParams struct {
	// IsUnspecified indicates whether the server is listening on a wildcard
	// address, "0.0.0.0" for IPv4 and "::" for IPv6. Only when this is set to
	// true, do we consider the destination prefixes specified in the filter
	// chain match criteria.
	IsUnspecifiedListener bool
	// DestAddr is the local address of an incoming connection.
	DestAddr net.IP
	// SourceAddr is the remote address of an incoming connection.
	SourceAddr net.IP
	// SourcePort is the remote port of an incoming connection.
	SourcePort int
}

FilterChainLookupParams wraps parameters to be passed to Lookup.

type FilterChainManager

type FilterChainManager struct {

	// RouteConfigNames are the route configuration names which need to be
	// dynamically queried for RDS Configuration for any FilterChains which
	// specify to load RDS Configuration dynamically.
	RouteConfigNames map[string]bool
	// contains filtered or unexported fields
}

FilterChainManager contains all the match criteria specified through all filter chains in a single Listener resource. It also contains the default filter chain specified in the Listener resource. It provides two important pieces of functionality:

  1. Validate the filter chains in an incoming Listener resource to make sure that there aren't filter chains which contain the same match criteria.
  2. As part of performing the above validation, it builds an internal data structure which will if used to look up the matching filter chain at connection time.

The logic specified in the documentation around the xDS FilterChainMatch proto mentions 8 criteria to match on. The following order applies:

1. Destination port. 2. Destination IP address. 3. Server name (e.g. SNI for TLS protocol), 4. Transport protocol. 5. Application protocols (e.g. ALPN for TLS protocol). 6. Source type (e.g. any, local or external network). 7. Source IP address. 8. Source port.

func NewFilterChainManager

func NewFilterChainManager(lis *v3listenerpb.Listener) (*FilterChainManager, error)

NewFilterChainManager parses the received Listener resource and builds a FilterChainManager. Returns a non-nil error on validation failures.

This function is only exported so that tests outside of this package can create a FilterChainManager.

func (*FilterChainManager) Lookup

Lookup returns the most specific matching filter chain to be used for an incoming connection on the server side.

Returns a non-nil error if no matching filter chain could be found or multiple matching filter chains were found, and in both cases, the incoming connection must be dropped.

func (*FilterChainManager) Validate

func (fci *FilterChainManager) Validate(f func(fc *FilterChain) error) error

Validate takes a function to validate the FilterChains in this manager.

type HTTPFilter

type HTTPFilter struct {
	// Name is an arbitrary name of the filter.  Used for applying override
	// settings in virtual host / route / weighted cluster configuration (not
	// yet supported).
	Name string
	// Filter is the HTTP filter found in the registry for the config type.
	Filter httpfilter.Filter
	// Config contains the filter's configuration
	Config httpfilter.FilterConfig
}

HTTPFilter represents one HTTP filter from an LDS response's HTTP connection manager field.

type HashPolicy

type HashPolicy struct {
	HashPolicyType HashPolicyType
	Terminal       bool
	// Fields used for type HEADER.
	HeaderName        string
	Regex             *regexp.Regexp
	RegexSubstitution string
}

HashPolicy specifies the HashPolicy if the upstream cluster uses a hashing load balancer.

type HashPolicyType

type HashPolicyType int

HashPolicyType specifies the type of HashPolicy from a received RDS Response.

const (
	// HashPolicyTypeHeader specifies to hash a Header in the incoming request.
	HashPolicyTypeHeader HashPolicyType = iota
	// HashPolicyTypeChannelID specifies to hash a unique Identifier of the
	// Channel. This is a 64-bit random int computed at initialization time.
	HashPolicyTypeChannelID
)

type HeaderMatcher

type HeaderMatcher struct {
	Name         string
	InvertMatch  *bool
	ExactMatch   *string
	RegexMatch   *regexp.Regexp
	PrefixMatch  *string
	SuffixMatch  *string
	RangeMatch   *Int64Range
	PresentMatch *bool
}

HeaderMatcher represents header matchers.

type InboundListenerConfig

type InboundListenerConfig struct {
	// Address is the local address on which the inbound listener is expected to
	// accept incoming connections.
	Address string
	// Port is the local port on which the inbound listener is expected to
	// accept incoming connections.
	Port string
	// FilterChains is the list of filter chains associated with this listener.
	FilterChains *FilterChainManager
}

InboundListenerConfig contains information about the inbound listener, i.e the server-side listener.

type Int64Range

type Int64Range struct {
	Start int64
	End   int64
}

Int64Range is a range for header range match.

type ListenerResourceData

type ListenerResourceData struct {
	ResourceData

	// TODO: We have always stored update structs by value. See if this can be
	// switched to a pointer?
	Resource ListenerUpdate
}

ListenerResourceData wraps the configuration of a Listener resource as received from the management server.

Implements the ResourceData interface.

func (*ListenerResourceData) Equal

func (l *ListenerResourceData) Equal(other ResourceData) bool

Equal returns true if other is equal to l.

func (*ListenerResourceData) Raw

func (l *ListenerResourceData) Raw() *anypb.Any

Raw returns the underlying raw protobuf form of the listener resource.

func (*ListenerResourceData) ToJSON

func (l *ListenerResourceData) ToJSON() string

ToJSON returns a JSON string representation of the resource data.

type ListenerUpdate

type ListenerUpdate struct {
	// RouteConfigName is the route configuration name corresponding to the
	// target which is being watched through LDS.
	//
	// Exactly one of RouteConfigName and InlineRouteConfig is set.
	RouteConfigName string
	// InlineRouteConfig is the inline route configuration (RDS response)
	// returned inside LDS.
	//
	// Exactly one of RouteConfigName and InlineRouteConfig is set.
	InlineRouteConfig *RouteConfigUpdate

	// MaxStreamDuration contains the HTTP connection manager's
	// common_http_protocol_options.max_stream_duration field, or zero if
	// unset.
	MaxStreamDuration time.Duration
	// HTTPFilters is a list of HTTP filters (name, config) from the LDS
	// response.
	HTTPFilters []HTTPFilter
	// InboundListenerCfg contains inbound listener configuration.
	InboundListenerCfg *InboundListenerConfig

	// Raw is the resource from the xds response.
	Raw *anypb.Any
}

ListenerUpdate contains information received in an LDS response, which is of interest to the registered LDS watcher.

type ListenerUpdateErrTuple

type ListenerUpdateErrTuple struct {
	Update ListenerUpdate
	Err    error
}

ListenerUpdateErrTuple is a tuple with the update and error. It contains the results from unmarshal functions. It's used to pass unmarshal results of multiple resources together, e.g. in maps like `map[string]{Update,error}`.

type ListenerWatcher

type ListenerWatcher interface {
	// OnUpdate is invoked to report an update for the resource being watched.
	OnUpdate(*ListenerResourceData)

	// OnError is invoked under different error conditions including but not
	// limited to the following:
	//	- authority mentioned in the resource is not found
	//	- resource name parsing error
	//	- resource deserialization error
	//	- resource validation error
	//	- ADS stream failure
	//	- connection failure
	OnError(error)

	// OnResourceDoesNotExist is invoked for a specific error condition where
	// the requested resource is not found on the xDS management server.
	OnResourceDoesNotExist()
}

ListenerWatcher wraps the callbacks to be invoked for different events corresponding to the listener resource being watched.

type Locality

type Locality struct {
	Endpoints []Endpoint
	ID        internal.LocalityID
	Priority  uint32
	Weight    uint32
}

Locality contains information of a locality.

type Name

type Name struct {
	Scheme    string
	Authority string
	Type      string
	ID        string

	ContextParams map[string]string
	// contains filtered or unexported fields
}

Name contains the parsed component of an xDS resource name.

An xDS resource name is in the format of xdstp://[{authority}]/{resource type}/{id/*}?{context parameters}{#processing directive,*}

See https://github.com/cncf/xds/blob/main/proposals/TP1-xds-transport-next.md#uri-based-xds-resource-names for details, and examples.

func ParseName

func ParseName(name string) *Name

ParseName splits the name and returns a struct representation of the Name.

If the name isn't a valid new-style xDS name, field ID is set to the input. Note that this is not an error, because we still support the old-style resource names (those not starting with "xdstp:").

The caller can tell if the parsing is successful by checking the returned Scheme.

func (*Name) String

func (n *Name) String() string

String returns a canonicalized string of name. The context parameters are sorted by the keys.

type OutlierDetection

type OutlierDetection struct {
	// Interval is the time interval between ejection analysis sweeps. This can
	// result in both new ejections as well as addresses being returned to
	// service. Defaults to 10s.
	Interval time.Duration
	// BaseEjectionTime is the base time that a host is ejected for. The real
	// time is equal to the base time multiplied by the number of times the host
	// has been ejected and is capped by MaxEjectionTime. Defaults to 30s.
	BaseEjectionTime time.Duration
	// MaxEjectionTime is the maximum time that an address is ejected for. If
	// not specified, the default value (300s) or the BaseEjectionTime value is
	// applied, whichever is larger.
	MaxEjectionTime time.Duration
	// MaxEjectionPercent is the maximum % of an upstream cluster that can be
	// ejected due to outlier detection. Defaults to 10% but will eject at least
	// one host regardless of the value.
	MaxEjectionPercent uint32
	// SuccessRateStdevFactor is used to determine the ejection threshold for
	// success rate outlier ejection. The ejection threshold is the difference
	// between the mean success rate, and the product of this factor and the
	// standard deviation of the mean success rate: mean - (stdev *
	// success_rate_stdev_factor). This factor is divided by a thousand to get a
	// double. That is, if the desired factor is 1.9, the runtime value should
	// be 1900. Defaults to 1900.
	SuccessRateStdevFactor uint32
	// EnforcingSuccessRate is the % chance that a host will be actually ejected
	// when an outlier status is detected through success rate statistics. This
	// setting can be used to disable ejection or to ramp it up slowly. Defaults
	// to 100.
	EnforcingSuccessRate uint32
	// SuccessRateMinimumHosts is the number of hosts in a cluster that must
	// have enough request volume to detect success rate outliers. If the number
	// of hosts is less than this setting, outlier detection via success rate
	// statistics is not performed for any host in the cluster. Defaults to 5.
	SuccessRateMinimumHosts uint32
	// SuccessRateRequestVolume is the minimum number of total requests that
	// must be collected in one interval (as defined by the interval duration
	// above) to include this host in success rate based outlier detection. If
	// the volume is lower than this setting, outlier detection via success rate
	// statistics is not performed for that host. Defaults to 100.
	SuccessRateRequestVolume uint32
	// FailurePercentageThreshold is the failure percentage to use when
	// determining failure percentage-based outlier detection. If the failure
	// percentage of a given host is greater than or equal to this value, it
	// will be ejected. Defaults to 85.
	FailurePercentageThreshold uint32
	// EnforcingFailurePercentage is the % chance that a host will be actually
	// ejected when an outlier status is detected through failure percentage
	// statistics. This setting can be used to disable ejection or to ramp it up
	// slowly. Defaults to 0.
	EnforcingFailurePercentage uint32
	// FailurePercentageMinimumHosts is the minimum number of hosts in a cluster
	// in order to perform failure percentage-based ejection. If the total
	// number of hosts in the cluster is less than this value, failure
	// percentage-based ejection will not be performed. Defaults to 5.
	FailurePercentageMinimumHosts uint32
	// FailurePercentageRequestVolume is the minimum number of total requests
	// that must be collected in one interval (as defined by the interval
	// duration above) to perform failure percentage-based ejection for this
	// host. If the volume is lower than this setting, failure percentage-based
	// ejection will not be performed for this host. Defaults to 50.
	FailurePercentageRequestVolume uint32
}

OutlierDetection is the outlier detection configuration for a cluster.

type OverloadDropConfig

type OverloadDropConfig struct {
	Category    string
	Numerator   uint32
	Denominator uint32
}

OverloadDropConfig contains the config to drop overloads.

type Producer

type Producer interface {
	// WatchResource uses xDS to discover the resource associated with the
	// provided resource name. The resource type implementation determines how
	// xDS requests are sent out and how responses are deserialized and
	// validated. Upon receipt of a response from the management server, an
	// appropriate callback on the watcher is invoked.
	WatchResource(rType Type, resourceName string, watcher ResourceWatcher) (cancel func())
}

Producer contains a single method to discover resource configuration from a remote management server using xDS APIs.

The xdsclient package provides a concrete implementation of this interface.

type ResourceData

type ResourceData interface {

	// Equal returns true if the passed in resource data is equal to that of the
	// receiver.
	Equal(ResourceData) bool

	// ToJSON returns a JSON string representation of the resource data.
	ToJSON() string

	Raw() *anypb.Any
	// contains filtered or unexported methods
}

ResourceData contains the configuration data sent by the xDS management server, associated with the resource being watched. Every resource type must provide an implementation of this interface to represent the configuration received from the xDS management server.

type ResourceType

type ResourceType int

ResourceType identifies resources in a transport protocol agnostic way. These will be used in transport version agnostic code, while the versioned API clients will map these to appropriate version URLs.

const (
	UnknownResource ResourceType = iota
	ListenerResource
	HTTPConnManagerResource
	RouteConfigResource
	ClusterResource
	EndpointsResource
)

Version agnostic resource type constants.

func (ResourceType) String

func (r ResourceType) String() string

type ResourceWatcher

type ResourceWatcher interface {
	// OnUpdate is invoked to report an update for the resource being watched.
	// The ResourceData parameter needs to be type asserted to the appropriate
	// type for the resource being watched.
	OnUpdate(ResourceData)

	// OnError is invoked under different error conditions including but not
	// limited to the following:
	//	- authority mentioned in the resource is not found
	//	- resource name parsing error
	//	- resource deserialization error
	//	- resource validation error
	//	- ADS stream failure
	//	- connection failure
	OnError(error)

	// OnResourceDoesNotExist is invoked for a specific error condition where
	// the requested resource is not found on the xDS management server.
	OnResourceDoesNotExist()
}

ResourceWatcher wraps the callbacks to be invoked for different events corresponding to the resource being watched.

type RetryBackoff

type RetryBackoff struct {
	BaseInterval time.Duration // initial backoff duration between attempts
	MaxInterval  time.Duration // maximum backoff duration
}

RetryBackoff describes the backoff policy for retries.

type RetryConfig

type RetryConfig struct {
	// RetryOn is a set of status codes on which to retry.  Only Canceled,
	// DeadlineExceeded, Internal, ResourceExhausted, and Unavailable are
	// supported; any other values will be omitted.
	RetryOn      map[codes.Code]bool
	NumRetries   uint32       // maximum number of retry attempts
	RetryBackoff RetryBackoff // retry backoff policy
}

RetryConfig contains all retry-related configuration in either a VirtualHost or Route.

type Route

type Route struct {
	Path   *string
	Prefix *string
	Regex  *regexp.Regexp
	// Indicates if prefix/path matching should be case insensitive. The default
	// is false (case sensitive).
	CaseInsensitive bool
	Headers         []*HeaderMatcher
	Fraction        *uint32

	HashPolicies []*HashPolicy

	// If the matchers above indicate a match, the below configuration is used.
	// If MaxStreamDuration is nil, it indicates neither of the route action's
	// max_stream_duration fields (grpc_timeout_header_max nor
	// max_stream_duration) were set.  In this case, the ListenerUpdate's
	// MaxStreamDuration field should be used.  If MaxStreamDuration is set to
	// an explicit zero duration, the application's deadline should be used.
	MaxStreamDuration *time.Duration
	// HTTPFilterConfigOverride contains any HTTP filter config overrides for
	// the route which may be present.  An individual filter's override may be
	// unused if the matching WeightedCluster contains an override for that
	// filter.
	HTTPFilterConfigOverride map[string]httpfilter.FilterConfig
	RetryConfig              *RetryConfig

	ActionType RouteActionType

	// Only one of the following fields (WeightedClusters or
	// ClusterSpecifierPlugin) will be set for a route.
	WeightedClusters map[string]WeightedCluster
	// ClusterSpecifierPlugin is the name of the Cluster Specifier Plugin that
	// this Route is linked to, if specified by xDS.
	ClusterSpecifierPlugin string
}

Route is both a specification of how to match a request as well as an indication of the action to take upon match.

type RouteActionType

type RouteActionType int

RouteActionType is the action of the route from a received RDS response.

const (
	// RouteActionUnsupported are routing types currently unsupported by grpc.
	// According to A36, "A Route with an inappropriate action causes RPCs
	// matching that route to fail."
	RouteActionUnsupported RouteActionType = iota
	// RouteActionRoute is the expected route type on the client side. Route
	// represents routing a request to some upstream cluster. On the client
	// side, if an RPC matches to a route that is not RouteActionRoute, the RPC
	// will fail according to A36.
	RouteActionRoute
	// RouteActionNonForwardingAction is the expected route type on the server
	// side. NonForwardingAction represents when a route will generate a
	// response directly, without forwarding to an upstream host.
	RouteActionNonForwardingAction
)

type RouteConfigResourceData

type RouteConfigResourceData struct {
	ResourceData

	// TODO: We have always stored update structs by value. See if this can be
	// switched to a pointer?
	Resource RouteConfigUpdate
}

RouteConfigResourceData wraps the configuration of a RouteConfiguration resource as received from the management server.

Implements the ResourceData interface.

func (*RouteConfigResourceData) Equal

func (r *RouteConfigResourceData) Equal(other ResourceData) bool

Equal returns true if other is equal to r.

func (*RouteConfigResourceData) Raw

func (r *RouteConfigResourceData) Raw() *anypb.Any

Raw returns the underlying raw protobuf form of the route configuration resource.

func (*RouteConfigResourceData) ToJSON

func (r *RouteConfigResourceData) ToJSON() string

ToJSON returns a JSON string representation of the resource data.

type RouteConfigUpdate

type RouteConfigUpdate struct {
	VirtualHosts []*VirtualHost
	// ClusterSpecifierPlugins are the LB Configurations for any
	// ClusterSpecifierPlugins referenced by the Route Table.
	ClusterSpecifierPlugins map[string]clusterspecifier.BalancerConfig
	// Raw is the resource from the xds response.
	Raw *anypb.Any
}

RouteConfigUpdate contains information received in an RDS response, which is of interest to the registered RDS watcher.

type RouteConfigUpdateErrTuple

type RouteConfigUpdateErrTuple struct {
	Update RouteConfigUpdate
	Err    error
}

RouteConfigUpdateErrTuple is a tuple with the update and error. It contains the results from unmarshal functions. It's used to pass unmarshal results of multiple resources together, e.g. in maps like `map[string]{Update,error}`.

type RouteConfigWatcher

type RouteConfigWatcher interface {
	// OnUpdate is invoked to report an update for the resource being watched.
	OnUpdate(*RouteConfigResourceData)

	// OnError is invoked under different error conditions including but not
	// limited to the following:
	//	- authority mentioned in the resource is not found
	//	- resource name parsing error
	//	- resource deserialization error
	//	- resource validation error
	//	- ADS stream failure
	//	- connection failure
	OnError(error)

	// OnResourceDoesNotExist is invoked for a specific error condition where
	// the requested resource is not found on the xDS management server.
	OnResourceDoesNotExist()
}

RouteConfigWatcher wraps the callbacks to be invoked for different events corresponding to the route configuration resource being watched.

type RouteWithInterceptors

type RouteWithInterceptors struct {
	// M is the matcher used to match to this route.
	M *CompositeMatcher
	// ActionType is the type of routing action to initiate once matched to.
	ActionType RouteActionType
	// Interceptors are interceptors instantiated for this route. These will be
	// constructed from a combination of the top level configuration and any
	// HTTP Filter overrides present in Virtual Host or Route.
	Interceptors []resolver.ServerInterceptor
}

RouteWithInterceptors captures information in a Route, and contains a usable matcher and also instantiated HTTP Filters.

type SecurityConfig

type SecurityConfig struct {
	// RootInstanceName identifies the certProvider plugin to be used to fetch
	// root certificates. This instance name will be resolved to the plugin name
	// and its associated configuration from the certificate_providers field of
	// the bootstrap file.
	RootInstanceName string
	// RootCertName is the certificate name to be passed to the plugin (looked
	// up from the bootstrap file) while fetching root certificates.
	RootCertName string
	// IdentityInstanceName identifies the certProvider plugin to be used to
	// fetch identity certificates. This instance name will be resolved to the
	// plugin name and its associated configuration from the
	// certificate_providers field of the bootstrap file.
	IdentityInstanceName string
	// IdentityCertName is the certificate name to be passed to the plugin
	// (looked up from the bootstrap file) while fetching identity certificates.
	IdentityCertName string
	// SubjectAltNameMatchers is an optional list of match criteria for SANs
	// specified on the peer certificate. Used only on the client-side.
	//
	// Some intricacies:
	// - If this field is empty, then any peer certificate is accepted.
	// - If the peer certificate contains a wildcard DNS SAN, and an `exact`
	//   matcher is configured, a wildcard DNS match is performed instead of a
	//   regular string comparison.
	SubjectAltNameMatchers []matcher.StringMatcher
	// RequireClientCert indicates if the server handshake process expects the
	// client to present a certificate. Set to true when performing mTLS. Used
	// only on the server-side.
	RequireClientCert bool
}

SecurityConfig contains the security configuration received as part of the Cluster resource on the client-side, and as part of the Listener resource on the server-side.

func (*SecurityConfig) Equal

func (sc *SecurityConfig) Equal(other *SecurityConfig) bool

Equal returns true if sc is equal to other.

type ServiceStatus

type ServiceStatus int

ServiceStatus is the status of the update.

const (
	// ServiceStatusUnknown is the default state, before a watch is started for
	// the resource.
	ServiceStatusUnknown ServiceStatus = iota
	// ServiceStatusRequested is when the watch is started, but before and
	// response is received.
	ServiceStatusRequested
	// ServiceStatusNotExist is when the resource doesn't exist in
	// state-of-the-world responses (e.g. LDS and CDS), which means the resource
	// is removed by the management server.
	ServiceStatusNotExist // Resource is removed in the server, in LDS/CDS.
	// ServiceStatusACKed is when the resource is ACKed.
	ServiceStatusACKed
	// ServiceStatusNACKed is when the resource is NACKed.
	ServiceStatusNACKed
)

type SourceType

type SourceType int

SourceType specifies the connection source IP match type.

const (
	// SourceTypeAny matches connection attempts from any source.
	SourceTypeAny SourceType = iota
	// SourceTypeSameOrLoopback matches connection attempts from the same host.
	SourceTypeSameOrLoopback
	// SourceTypeExternal matches connection attempts from a different host.
	SourceTypeExternal
)

type Type

type Type interface {
	// TypeURL is the xDS type URL of this resource type for v3 transport.
	TypeURL() string

	// TypeEnum is an enumerated value for this resource type. This can be used
	// for logging/debugging purposes, as well in cases where the resource type
	// is to be uniquely identified but the actual functionality provided by the
	// resource type is not required.
	//
	// TODO: once Type is renamed to ResourceType, rename ResourceType to
	// ResourceTypeEnum.
	TypeEnum() ResourceType

	// AllResourcesRequiredInSotW indicates whether this resource type requires
	// that all resources be present in every SotW response from the server. If
	// true, a response that does not include a previously seen resource will be
	// interpreted as a deletion of that resource.
	AllResourcesRequiredInSotW() bool

	// Decode deserializes and validates an xDS resource serialized inside the
	// provided `Any` proto, as received from the xDS management server.
	//
	// If protobuf deserialization fails or resource validation fails,
	// returns a non-nil error. Otherwise, returns a fully populated
	// DecodeResult.
	Decode(*DecodeOptions, *anypb.Any) (*DecodeResult, error)
}

Type wraps all resource-type specific functionality. Each supported resource type will provide an implementation of this interface.

type UpdateErrorMetadata

type UpdateErrorMetadata struct {
	// Version is the version of the NACKed response.
	Version string
	// Err contains why the response was NACKed.
	Err error
	// Timestamp is when the NACKed response was received.
	Timestamp time.Time
}

UpdateErrorMetadata is part of UpdateMetadata. It contains the error state when a response is NACKed.

type UpdateMetadata

type UpdateMetadata struct {
	// Status is the status of this resource, e.g. ACKed, NACKed, or
	// Not_exist(removed).
	Status ServiceStatus
	// Version is the version of the xds response. Note that this is the version
	// of the resource in use (previous ACKed). If a response is NACKed, the
	// NACKed version is in ErrState.
	Version string
	// Timestamp is when the response is received.
	Timestamp time.Time
	// ErrState is set when the update is NACKed.
	ErrState *UpdateErrorMetadata
}

UpdateMetadata contains the metadata for each update, including timestamp, raw message, and so on.

type UpdateValidatorFunc

type UpdateValidatorFunc func(interface{}) error

UpdateValidatorFunc performs validations on update structs using context/logic available at the xdsClient layer. Since these validation are performed on internal update structs, they can be shared between different API clients.

type UpdateWithMD

type UpdateWithMD struct {
	MD  UpdateMetadata
	Raw *anypb.Any
}

UpdateWithMD contains the raw message of the update and the metadata, including version, raw message, timestamp.

This is to be used for config dump and CSDS, not directly by users (like resolvers/balancers).

type VirtualHost

type VirtualHost struct {
	Domains []string
	// Routes contains a list of routes, each containing matchers and
	// corresponding action.
	Routes []*Route
	// HTTPFilterConfigOverride contains any HTTP filter config overrides for
	// the virtual host which may be present.  An individual filter's override
	// may be unused if the matching Route contains an override for that
	// filter.
	HTTPFilterConfigOverride map[string]httpfilter.FilterConfig
	RetryConfig              *RetryConfig
}

VirtualHost contains the routes for a list of Domains.

Note that the domains in this slice can be a wildcard, not an exact string. The consumer of this struct needs to find the best match for its hostname.

func FindBestMatchingVirtualHost

func FindBestMatchingVirtualHost(host string, vHosts []*VirtualHost) *VirtualHost

FindBestMatchingVirtualHost returns the virtual host whose domains field best matches host

The domains field support 4 different matching pattern types:

- Exact match
- Suffix match (e.g. “*ABC”)
- Prefix match (e.g. “ABC*)
- Universal match (e.g. “*”)

The best match is defined as:
- A match is better if it’s matching pattern type is better.
  * Exact match > suffix match > prefix match > universal match.

- If two matches are of the same pattern type, the longer match is
  better.
  * This is to compare the length of the matching pattern, e.g. “*ABCDE” >
    “*ABC”

type VirtualHostWithInterceptors

type VirtualHostWithInterceptors struct {
	// Domains are the domain names which map to this Virtual Host. On the
	// server side, this will be dictated by the :authority header of the
	// incoming RPC.
	Domains []string
	// Routes are the Routes for this Virtual Host.
	Routes []RouteWithInterceptors
}

VirtualHostWithInterceptors captures information present in a VirtualHost update, and also contains routes with instantiated HTTP Filters.

func FindBestMatchingVirtualHostServer

func FindBestMatchingVirtualHostServer(authority string, vHosts []VirtualHostWithInterceptors) *VirtualHostWithInterceptors

FindBestMatchingVirtualHostServer returns the virtual host whose domains field best matches authority.

type WeightedCluster

type WeightedCluster struct {
	// Weight is the relative weight of the cluster.  It will never be zero.
	Weight uint32
	// HTTPFilterConfigOverride contains any HTTP filter config overrides for
	// the weighted cluster which may be present.
	HTTPFilterConfigOverride map[string]httpfilter.FilterConfig
}

WeightedCluster contains settings for an xds ActionType.WeightedCluster.

Directories

Path Synopsis
Package version defines constants to distinguish between supported xDS API versions.
Package version defines constants to distinguish between supported xDS API versions.

Jump to

Keyboard shortcuts

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