Documentation ¶
Overview ¶
Package xdsclient implements a full fledged gRPC client for the xDS API used by the xds resolver and balancer implementations.
Index ¶
- Variables
- func ClearAllCountersForTesting()
- func ClearCounterForTesting(clusterName, edsServiceName string)
- func IsClusterResource(url string) bool
- func IsEndpointsResource(url string) bool
- func IsHTTPConnManagerResource(url string) bool
- func IsListenerResource(url string) bool
- func IsRouteConfigResource(url string) bool
- func NewErrorf(t ErrorType, format string, args ...interface{}) error
- func RegisterAPIClientBuilder(b APIClientBuilder)
- func SetClient(state resolver.State, c XDSClient) resolver.State
- type APIClient
- type APIClientBuilder
- type BuildOptions
- type ClusterLBPolicyRingHash
- type ClusterRequestsCounter
- type ClusterType
- type ClusterUpdate
- type ClusterUpdateErrTuple
- type CompositeMatcher
- type Endpoint
- type EndpointHealthStatus
- type EndpointsUpdate
- type EndpointsUpdateErrTuple
- type ErrResourceTypeUnsupported
- type ErrorType
- type FilterChain
- type FilterChainLookupParams
- type FilterChainManager
- type HTTPFilter
- type HashPolicy
- type HashPolicyType
- type HeaderMatcher
- type InboundListenerConfig
- type Int64Range
- type ListenerUpdate
- type ListenerUpdateErrTuple
- type Locality
- type OverloadDropConfig
- type ResourceType
- type RetryBackoff
- type RetryConfig
- type Route
- type RouteAction
- type RouteConfigUpdate
- type RouteConfigUpdateErrTuple
- type RouteWithInterceptors
- type SecurityConfig
- type ServiceStatus
- type SourceType
- type TransportHelper
- type UnmarshalOptions
- type UpdateErrorMetadata
- type UpdateHandler
- type UpdateMetadata
- func UnmarshalCluster(opts *UnmarshalOptions) (map[string]ClusterUpdateErrTuple, UpdateMetadata, error)
- func UnmarshalEndpoints(opts *UnmarshalOptions) (map[string]EndpointsUpdateErrTuple, UpdateMetadata, error)
- func UnmarshalListener(opts *UnmarshalOptions) (map[string]ListenerUpdateErrTuple, UpdateMetadata, error)
- func UnmarshalRouteConfig(opts *UnmarshalOptions) (map[string]RouteConfigUpdateErrTuple, UpdateMetadata, error)
- type UpdateValidatorFunc
- type UpdateWithMD
- type VersionedClient
- type VirtualHost
- type VirtualHostWithInterceptors
- type WeightedCluster
- type XDSClient
- func FromResolverState(state resolver.State) XDSClient
- func New() (XDSClient, error)
- func NewClientWithBootstrapContents(contents []byte) (XDSClient, error)
- func NewWithConfig(config *bootstrap.Config) (XDSClient, error)
- func NewWithConfigForTesting(config *bootstrap.Config, watchExpiryTimeout time.Duration) (XDSClient, error)
Constants ¶
This section is empty.
Variables ¶
var RandInt63n = grpcrand.Int63n
RandInt63n overwrites grpcrand for control in tests.
Functions ¶
func ClearAllCountersForTesting ¶ added in v1.40.0
func ClearAllCountersForTesting()
ClearAllCountersForTesting clears all the counters. Should be only used in tests.
func ClearCounterForTesting ¶
func ClearCounterForTesting(clusterName, edsServiceName string)
ClearCounterForTesting clears the counter for the service. Should be only used in tests.
func IsClusterResource ¶
IsClusterResource returns true if the provider URL corresponds to an xDS Cluster resource.
func IsEndpointsResource ¶
IsEndpointsResource returns true if the provider URL corresponds to an xDS Endpoints resource.
func IsHTTPConnManagerResource ¶
IsHTTPConnManagerResource returns true if the provider URL corresponds to an xDS HTTPConnManager resource.
func IsListenerResource ¶
IsListenerResource returns true if the provider URL corresponds to an xDS Listener resource.
func IsRouteConfigResource ¶
IsRouteConfigResource returns true if the provider URL corresponds to an xDS RouteConfig resource.
func NewErrorf ¶
NewErrorf creates an xds client error. The callbacks are called with this error, to pass additional information about the error.
func RegisterAPIClientBuilder ¶
func RegisterAPIClientBuilder(b APIClientBuilder)
RegisterAPIClientBuilder registers a client builder for xDS transport protocol version specified by b.Version().
NOTE: this function must only be called during initialization time (i.e. in an init() function), and is not thread-safe. If multiple builders are registered for the same version, the one registered last will take effect.
Types ¶
type APIClient ¶
type APIClient interface { // AddWatch adds a watch for an xDS resource given its type and name. AddWatch(ResourceType, string) // RemoveWatch cancels an already registered watch for an xDS resource // given its type and name. RemoveWatch(ResourceType, string) // Close cleans up resources allocated by the API client. Close() // contains filtered or unexported methods }
APIClient represents the functionality provided by transport protocol version specific implementations of the xDS client.
TODO: unexport this interface and all the methods after the PR to make xdsClient sharable by clients. AddWatch and RemoveWatch are exported for v2/v3 to override because they need to keep track of LDS name for RDS to use. After the share xdsClient change, that's no longer necessary. After that, we will still keep this interface for testing purposes.
type APIClientBuilder ¶
type APIClientBuilder interface { // Build builds a transport protocol specific implementation of the xDS // client based on the provided clientConn to the management server and the // provided options. Build(*grpc.ClientConn, BuildOptions) (APIClient, error) // Version returns the xDS transport protocol version used by clients build // using this builder. Version() version.TransportAPI }
APIClientBuilder creates an xDS client for a specific xDS transport protocol version.
type BuildOptions ¶
type BuildOptions struct { // Parent is a top-level xDS client which has the intelligence to take // appropriate action based on xDS responses received from the management // server. Parent UpdateHandler // Validator performs post unmarshal validation checks. Validator UpdateValidatorFunc // NodeProto contains the Node proto to be used in xDS requests. The actual // type depends on the transport protocol version used. NodeProto proto.Message // Backoff returns the amount of time to backoff before retrying broken // streams. Backoff func(int) time.Duration // Logger provides enhanced logging capabilities. Logger *grpclog.PrefixLogger }
BuildOptions contains options to be passed to client builders.
type ClusterLBPolicyRingHash ¶ added in v1.41.0
ClusterLBPolicyRingHash represents ring_hash lb policy, and also contains its config.
type ClusterRequestsCounter ¶ added in v1.40.0
type ClusterRequestsCounter struct { ClusterName string EDSServiceName string // contains filtered or unexported fields }
ClusterRequestsCounter is used to track the total inflight requests for a service with the provided name.
func GetClusterRequestsCounter ¶ added in v1.40.0
func GetClusterRequestsCounter(clusterName, edsServiceName string) *ClusterRequestsCounter
GetClusterRequestsCounter returns the ClusterRequestsCounter with the provided serviceName. If one does not exist, it creates it.
func (*ClusterRequestsCounter) EndRequest ¶ added in v1.40.0
func (c *ClusterRequestsCounter) EndRequest()
EndRequest ends a request for a service, decrementing its number of requests by 1.
func (*ClusterRequestsCounter) StartRequest ¶ added in v1.40.0
func (c *ClusterRequestsCounter) StartRequest(max uint32) error
StartRequest starts a request for a cluster, incrementing its number of requests by 1. Returns an error if the max number of requests is exceeded.
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 // EnableLRS indicates whether or not load should be reported through LRS. EnableLRS bool // 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 // 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 ¶ added in v1.41.0
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 CompositeMatcher ¶ added in v1.41.0
type CompositeMatcher struct {
// contains filtered or unexported fields
}
CompositeMatcher is a matcher that holds onto many matchers and aggregates the matching results.
func RouteToMatcher ¶ added in v1.41.0
func RouteToMatcher(r *Route) (*CompositeMatcher, error)
RouteToMatcher converts a route to a Matcher to match incoming RPC's against.
func (*CompositeMatcher) Match ¶ added in v1.41.0
func (a *CompositeMatcher) Match(info iresolver.RPCInfo) bool
Match returns true if all matchers return true.
func (*CompositeMatcher) String ¶ added in v1.41.0
func (a *CompositeMatcher) String() string
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 EndpointsUpdate ¶
type EndpointsUpdate struct { Drops []OverloadDropConfig Localities []Locality // Raw is the resource from the xds response. Raw *anypb.Any }
EndpointsUpdate contains an EDS update.
type EndpointsUpdateErrTuple ¶ added in v1.41.0
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 ErrResourceTypeUnsupported ¶
type ErrResourceTypeUnsupported struct {
ErrStr string
}
ErrResourceTypeUnsupported is an error used to indicate an unsupported xDS resource type. The wrapped ErrStr contains the details.
func (ErrResourceTypeUnsupported) Error ¶
func (e ErrResourceTypeUnsupported) Error() string
Error helps implements the error interface.
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 )
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. // // Only one of RouteConfigName and InlineRouteConfig is set. RouteConfigName string // InlineRouteConfig is the inline route configuration (RDS response) // returned for this filter chain. // // Only one of RouteConfigName and InlineRouteConfig is set. InlineRouteConfig *RouteConfigUpdate }
FilterChain captures information from within a FilterChain message in a Listener resource.
func (*FilterChain) ConstructUsableRouteConfiguration ¶ added in v1.41.0
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:
- Validate the filter chains in an incoming Listener resource to make sure that there aren't filter chains which contain the same match criteria.
- 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 ¶
func (fci *FilterChainManager) Lookup(params FilterChainLookupParams) (*FilterChain, error)
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.
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. In grpc-go, this will be done using the ClientConn pointer. 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 ¶
Int64Range is a range for header range match.
type ListenerUpdate ¶
type ListenerUpdate struct { // RouteConfigName is the route configuration name corresponding to the // target which is being watched through LDS. // // Only one of RouteConfigName and InlineRouteConfig is set. RouteConfigName string // InlineRouteConfig is the inline route configuration (RDS response) // returned inside LDS. // // Only 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 ¶ added in v1.41.0
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 Locality ¶
type Locality struct { Endpoints []Endpoint ID internal.LocalityID Priority uint32 Weight uint32 }
Locality contains information of a locality.
type OverloadDropConfig ¶
OverloadDropConfig contains the config to drop overloads.
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 RetryBackoff ¶ added in v1.41.0
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 ¶ added in v1.41.0
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. WeightedClusters map[string]WeightedCluster // 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 RouteAction RouteAction }
Route is both a specification of how to match a request as well as an indication of the action to take upon match.
type RouteAction ¶ added in v1.41.0
type RouteAction int
RouteAction 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 RouteAction = 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 RouteConfigUpdate ¶
type RouteConfigUpdate struct { VirtualHosts []*VirtualHost // 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 ¶ added in v1.41.0
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 RouteWithInterceptors ¶ added in v1.41.0
type RouteWithInterceptors struct { // M is the matcher used to match to this route. M *CompositeMatcher // RouteAction is the type of routing action to initiate once matched to. RouteAction RouteAction // 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 ¶ added in v1.41.0
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 TransportHelper ¶
type TransportHelper struct {
// contains filtered or unexported fields
}
TransportHelper contains all xDS transport protocol related functionality which is common across different versioned client implementations.
TransportHelper takes care of sending and receiving xDS requests and responses on an ADS stream. It also takes care of ACK/NACK handling. It delegates to the actual versioned client implementations wherever appropriate.
Implements the APIClient interface which makes it possible for versioned client implementations to embed this type, and thereby satisfy the interface requirements.
func NewTransportHelper ¶
func NewTransportHelper(vc VersionedClient, logger *grpclog.PrefixLogger, backoff func(int) time.Duration) *TransportHelper
NewTransportHelper creates a new transport helper to be used by versioned client implementations.
func (*TransportHelper) AddWatch ¶
func (t *TransportHelper) AddWatch(rType ResourceType, resourceName string)
AddWatch adds a watch for an xDS resource given its type and name.
func (*TransportHelper) Close ¶
func (t *TransportHelper) Close()
Close closes the transport helper.
func (*TransportHelper) RemoveWatch ¶
func (t *TransportHelper) RemoveWatch(rType ResourceType, resourceName string)
RemoveWatch cancels an already registered watch for an xDS resource given its type and name.
type UnmarshalOptions ¶ added in v1.42.0
type UnmarshalOptions struct { // Version is the version of the received response. Version string // Resources are the xDS resources resources in the received response. Resources []*anypb.Any // Logger is the prefix logger to be used during unmarshaling. Logger *grpclog.PrefixLogger // UpdateValidator is a post unmarshal validation check provided by the // upper layer. UpdateValidator UpdateValidatorFunc }
UnmarshalOptions wraps the input parameters for `UnmarshalXxx` functions.
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 UpdateHandler ¶
type UpdateHandler interface { // NewListeners handles updates to xDS listener resources. NewListeners(map[string]ListenerUpdateErrTuple, UpdateMetadata) // NewRouteConfigs handles updates to xDS RouteConfiguration resources. NewRouteConfigs(map[string]RouteConfigUpdateErrTuple, UpdateMetadata) // NewClusters handles updates to xDS Cluster resources. NewClusters(map[string]ClusterUpdateErrTuple, UpdateMetadata) // NewEndpoints handles updates to xDS ClusterLoadAssignment (or tersely // referred to as Endpoints) resources. NewEndpoints(map[string]EndpointsUpdateErrTuple, UpdateMetadata) // NewConnectionError handles connection errors from the xDS stream. The // error will be reported to all the resource watchers. NewConnectionError(err error) }
UpdateHandler receives and processes (by taking appropriate actions) xDS resource updates from an APIClient for a specific version.
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.
func UnmarshalCluster ¶
func UnmarshalCluster(opts *UnmarshalOptions) (map[string]ClusterUpdateErrTuple, UpdateMetadata, error)
UnmarshalCluster processes resources received in an CDS response, validates them, and transforms them into a native struct which contains only fields we are interested in.
func UnmarshalEndpoints ¶
func UnmarshalEndpoints(opts *UnmarshalOptions) (map[string]EndpointsUpdateErrTuple, UpdateMetadata, error)
UnmarshalEndpoints processes resources received in an EDS response, validates them, and transforms them into a native struct which contains only fields we are interested in.
func UnmarshalListener ¶
func UnmarshalListener(opts *UnmarshalOptions) (map[string]ListenerUpdateErrTuple, UpdateMetadata, error)
UnmarshalListener processes resources received in an LDS response, validates them, and transforms them into a native struct which contains only fields we are interested in.
func UnmarshalRouteConfig ¶
func UnmarshalRouteConfig(opts *UnmarshalOptions) (map[string]RouteConfigUpdateErrTuple, UpdateMetadata, error)
UnmarshalRouteConfig processes resources received in an RDS response, validates them, and transforms them into a native struct which contains only fields we are interested in. The provided hostname determines the route configuration resources of interest.
type UpdateValidatorFunc ¶ added in v1.42.0
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 VersionedClient ¶
type VersionedClient interface { // NewStream returns a new xDS client stream specific to the underlying // transport protocol version. NewStream(ctx context.Context) (grpc.ClientStream, error) // SendRequest constructs and sends out a DiscoveryRequest message specific // to the underlying transport protocol version. SendRequest(s grpc.ClientStream, resourceNames []string, rType ResourceType, version, nonce, errMsg string) error // RecvResponse uses the provided stream to receive a response specific to // the underlying transport protocol version. RecvResponse(s grpc.ClientStream) (proto.Message, error) // HandleResponse parses and validates the received response and notifies // the top-level client which in turn notifies the registered watchers. // // Return values are: resourceType, version, nonce, error. // If the provided protobuf message contains a resource type which is not // supported, implementations must return an error of type // ErrResourceTypeUnsupported. HandleResponse(proto.Message) (ResourceType, string, string, error) // NewLoadStatsStream returns a new LRS client stream specific to the underlying // transport protocol version. NewLoadStatsStream(ctx context.Context, cc *grpc.ClientConn) (grpc.ClientStream, error) // SendFirstLoadStatsRequest constructs and sends the first request on the // LRS stream. SendFirstLoadStatsRequest(s grpc.ClientStream) error // HandleLoadStatsResponse receives the first response from the server which // contains the load reporting interval and the clusters for which the // server asks the client to report load for. // // If the response sets SendAllClusters to true, the returned clusters is // nil. HandleLoadStatsResponse(s grpc.ClientStream) (clusters []string, _ time.Duration, _ error) // SendLoadStatsRequest will be invoked at regular intervals to send load // report with load data reported since the last time this method was // invoked. SendLoadStatsRequest(s grpc.ClientStream, loads []*load.Data) error }
VersionedClient is the interface to be provided by the transport protocol specific client implementations. This mainly deals with the actual sending and receiving of messages.
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 ¶ added in v1.41.0
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 ¶ added in v1.41.0
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 ¶ added in v1.41.0
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 RouteAction.WeightedCluster.
type XDSClient ¶
type XDSClient interface { WatchListener(string, func(ListenerUpdate, error)) func() WatchRouteConfig(string, func(RouteConfigUpdate, error)) func() WatchCluster(string, func(ClusterUpdate, error)) func() WatchEndpoints(clusterName string, edsCb func(EndpointsUpdate, error)) (cancel func()) ReportLoad(server string) (*load.Store, func()) DumpLDS() (string, map[string]UpdateWithMD) DumpRDS() (string, map[string]UpdateWithMD) DumpCDS() (string, map[string]UpdateWithMD) DumpEDS() (string, map[string]UpdateWithMD) BootstrapConfig() *bootstrap.Config Close() }
XDSClient is a full fledged gRPC client which queries a set of discovery APIs (collectively termed as xDS) on a remote management server, to discover various dynamic resources.
func FromResolverState ¶
FromResolverState returns the Client from state, or nil if not present.
func New ¶
New returns a new xdsClient configured by the bootstrap file specified in env variable GRPC_XDS_BOOTSTRAP or GRPC_XDS_BOOTSTRAP_CONFIG.
The returned xdsClient is a singleton. This function creates the xds client if it doesn't already exist.
Note that the first invocation of New() or NewWithConfig() sets the client singleton. The following calls will return the singleton xds client without checking or using the config.
func NewClientWithBootstrapContents ¶
NewClientWithBootstrapContents returns an xds client for this config, separate from the global singleton. This should be used for testing purposes only.
func NewWithConfig ¶
NewWithConfig returns a new xdsClient configured by the given config.
The returned xdsClient is a singleton. This function creates the xds client if it doesn't already exist.
Note that the first invocation of New() or NewWithConfig() sets the client singleton. The following calls will return the singleton xds client without checking or using the config.
This function is internal only, for c2p resolver and testing to use. DO NOT use this elsewhere. Use New() instead.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package bootstrap provides the functionality to initialize certain aspects of an xDS client by reading a bootstrap file.
|
Package bootstrap provides the functionality to initialize certain aspects of an xDS client by reading a bootstrap file. |
Package load provides functionality to record and maintain load data.
|
Package load provides functionality to record and maintain load data. |
Package v2 provides xDS v2 transport protocol specific functionality.
|
Package v2 provides xDS v2 transport protocol specific functionality. |
Package v3 provides xDS v3 transport protocol specific functionality.
|
Package v3 provides xDS v3 transport protocol specific functionality. |