client

package
v1.33.1 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2020 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Overview

Package client implementation a full fledged gRPC client for the xDS API used by the xds resolver and balancer implementations.

Index

Constants

This section is empty.

Variables

This section is empty.

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

func UnmarshalCluster

func UnmarshalCluster(resources []*anypb.Any, logger *grpclog.PrefixLogger) (map[string]ClusterUpdate, 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(resources []*anypb.Any, logger *grpclog.PrefixLogger) (map[string]EndpointsUpdate, 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(resources []*anypb.Any, logger *grpclog.PrefixLogger) (map[string]ListenerUpdate, 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(resources []*anypb.Any, hostname string, logger *grpclog.PrefixLogger) (map[string]RouteConfigUpdate, 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.

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

APIClient represents the functionality provided by transport protocol version specific implementations of the xDS client.

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 or server which has the intelligence to
	// take appropriate action based on xDS responses received from the
	// management server.
	Parent UpdateHandler
	// 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 Client

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

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

A single client object will be shared by the xds resolver and balancer implementations. But the same client can only be shared by the same parent ClientConn.

Implements UpdateHandler interface. TODO(easwars): Make a wrapper struct which implements this interface in the style of ccBalancerWrapper so that the Client type does not implement these exported methods.

func New

func New(opts Options) (*Client, error)

New returns a new xdsClient configured with opts.

func (*Client) Close

func (c *Client) Close()

Close closes the gRPC connection to the xDS server.

func (*Client) NewClusters

func (c *Client) NewClusters(updates map[string]ClusterUpdate)

NewClusters is called by the underlying xdsAPIClient when it receives an xDS response.

A response can contain multiple resources. They will be parsed and put in a map from resource name to the resource content.

func (*Client) NewEndpoints

func (c *Client) NewEndpoints(updates map[string]EndpointsUpdate)

NewEndpoints is called by the underlying xdsAPIClient when it receives an xDS response.

A response can contain multiple resources. They will be parsed and put in a map from resource name to the resource content.

func (*Client) NewListeners

func (c *Client) NewListeners(updates map[string]ListenerUpdate)

NewListeners is called by the underlying xdsAPIClient when it receives an xDS response.

A response can contain multiple resources. They will be parsed and put in a map from resource name to the resource content.

func (*Client) NewRouteConfigs

func (c *Client) NewRouteConfigs(updates map[string]RouteConfigUpdate)

NewRouteConfigs is called by the underlying xdsAPIClient when it receives an xDS response.

A response can contain multiple resources. They will be parsed and put in a map from resource name to the resource content.

func (*Client) ReportLoad

func (c *Client) ReportLoad(server string, clusterName string, loadStore lrs.Store) func()

ReportLoad sends the load of the given clusterName from loadStore to the given server. If the server is not an empty string, and is different from the xds server, a new ClientConn will be created.

The same options used for creating the Client will be used (including NodeProto, and dial options if necessary).

It returns a function to cancel the load reporting stream. If server is different from xds server, the ClientConn will also be closed.

func (*Client) WatchCluster

func (c *Client) WatchCluster(clusterName string, cb func(ClusterUpdate, error)) (cancel func())

WatchCluster uses CDS to discover information about the provided clusterName.

WatchCluster can be called multiple times, with same or different clusterNames. Each call will start an independent watcher for the resource.

Note that during race (e.g. an xDS response is received while the user is calling cancel()), there's a small window where the callback can be called after the watcher is canceled. The caller needs to handle this case.

func (*Client) WatchEndpoints

func (c *Client) WatchEndpoints(clusterName string, cb func(EndpointsUpdate, error)) (cancel func())

WatchEndpoints uses EDS to discover endpoints in the provided clusterName.

WatchEndpoints can be called multiple times, with same or different clusterNames. Each call will start an independent watcher for the resource.

Note that during race (e.g. an xDS response is received while the user is calling cancel()), there's a small window where the callback can be called after the watcher is canceled. The caller needs to handle this case.

func (*Client) WatchListener

func (c *Client) WatchListener(listener string, cb func(ListenerUpdate, error)) (cancel func())

WatchListener uses LDS to discover information about the provided listener.

WatchListener is expected to called only from the server side implementation of xDS. Clients will use WatchService instead.

Note that during race (e.g. an xDS response is received while the user is calling cancel()), there's a small window where the callback can be called after the watcher is canceled. The caller needs to handle this case.

func (*Client) WatchService

func (c *Client) WatchService(serviceName string, cb func(ServiceUpdate, error)) (cancel func())

WatchService uses LDS and RDS to discover information about the provided serviceName.

WatchService can only be called once. The second call will not start a watcher and the callback will get an error. It's this case because an xDS client is expected to be used only by one ClientConn.

Note that during race (e.g. an xDS response is received while the user is calling cancel()), there's a small window where the callback can be called after the watcher is canceled. The caller needs to handle this case.

type ClusterUpdate

type ClusterUpdate struct {
	// ServiceName is the service name corresponding to the clusterName which
	// is being watched for through CDS.
	ServiceName string
	// EnableLRS indicates whether or not load should be reported through LRS.
	EnableLRS bool
}

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

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
}

EndpointsUpdate contains an EDS update.

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

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
)

func ErrType

func ErrType(e error) ErrorType

ErrType returns the error's type.

type HeaderMatcher

type HeaderMatcher struct {
	Name         string      `json:"name"`
	InvertMatch  *bool       `json:"invertMatch,omitempty"`
	ExactMatch   *string     `json:"exactMatch,omitempty"`
	RegexMatch   *string     `json:"regexMatch,omitempty"`
	PrefixMatch  *string     `json:"prefixMatch,omitempty"`
	SuffixMatch  *string     `json:"suffixMatch,omitempty"`
	RangeMatch   *Int64Range `json:"rangeMatch,omitempty"`
	PresentMatch *bool       `json:"presentMatch,omitempty"`
}

HeaderMatcher represents header matchers.

type Int64Range

type Int64Range struct {
	Start int64 `json:"start"`
	End   int64 `json:"end"`
}

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.
	RouteConfigName string
}

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

type Locality

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

Locality contains information of a locality.

type Options

type Options struct {
	// Config contains a fully populated bootstrap config. It is the
	// responsibility of the caller to use some sane defaults here if the
	// bootstrap process returned with certain fields left unspecified.
	Config bootstrap.Config
	// DialOpts contains dial options to be used when dialing the xDS server.
	DialOpts []grpc.DialOption
	// TargetName is the target of the parent ClientConn.
	TargetName string
	// WatchExpiryTimeout is the amount of time the client is willing to wait
	// for the first response from the server for any resource being watched.
	// Expiry will not cause cancellation of the watch. It will only trigger the
	// invocation of the registered callback and it is left up to the caller to
	// decide whether or not they want to cancel the watch.
	//
	// If this field is left unspecified, a default value of 15 seconds will be
	// used. This is based on the default value of the initial_fetch_timeout
	// field in corepb.ConfigSource proto.
	WatchExpiryTimeout time.Duration
}

Options provides all parameters required for the creation of an xDS client.

type OverloadDropConfig

type OverloadDropConfig struct {
	Category    string
	Numerator   uint32
	Denominator uint32
}

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 Route

type Route struct {
	Path, Prefix, Regex *string
	Headers             []*HeaderMatcher
	Fraction            *uint32
	Action              map[string]uint32 // action is weighted clusters.
}

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

type RouteConfigUpdate

type RouteConfigUpdate struct {
	// Routes contains a list of routes, each containing matchers and
	// corresponding action.
	Routes []*Route
}

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

type ServiceUpdate

type ServiceUpdate struct {
	// Routes contain matchers+actions to route RPCs.
	Routes []*Route
}

ServiceUpdate contains information received from LDS and RDS responses, which is of interest to the registered service watcher.

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 UpdateHandler

type UpdateHandler interface {
	// NewListeners handles updates to xDS listener resources.
	NewListeners(map[string]ListenerUpdate)
	// NewRouteConfigs handles updates to xDS RouteConfiguration resources.
	NewRouteConfigs(map[string]RouteConfigUpdate)
	// NewClusters handles updates to xDS Cluster resources.
	NewClusters(map[string]ClusterUpdate)
	// NewEndpoints handles updates to xDS ClusterLoadAssignment (or tersely
	// referred to as Endpoints) resources.
	NewEndpoints(map[string]EndpointsUpdate)
}

UpdateHandler receives and processes (by taking appropriate actions) xDS resource updates from an APIClient for a specific version.

type VersionedClient

type VersionedClient interface {
	// NewStream returns a new grpc.ClientStream 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 string, nonce string) error

	// RecvResponse uses the provided stream to receive a response specific to
	// the underlying transport protocol version.
	RecvResponse(stream 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)
}

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.

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

Jump to

Keyboard shortcuts

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