...

Source file src/google.golang.org/grpc/resolver/resolver.go

Documentation: google.golang.org/grpc/resolver

     1  /*
     2   *
     3   * Copyright 2017 gRPC authors.
     4   *
     5   * Licensed under the Apache License, Version 2.0 (the "License");
     6   * you may not use this file except in compliance with the License.
     7   * You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   *
    17   */
    18  
    19  // Package resolver defines APIs for name resolution in gRPC.
    20  // All APIs in this package are experimental.
    21  package resolver
    22  
    23  import (
    24  	"context"
    25  	"fmt"
    26  	"net"
    27  	"net/url"
    28  	"strings"
    29  
    30  	"google.golang.org/grpc/attributes"
    31  	"google.golang.org/grpc/credentials"
    32  	"google.golang.org/grpc/internal"
    33  	"google.golang.org/grpc/serviceconfig"
    34  )
    35  
    36  var (
    37  	// m is a map from scheme to resolver builder.
    38  	m = make(map[string]Builder)
    39  	// defaultScheme is the default scheme to use.
    40  	defaultScheme = "passthrough"
    41  )
    42  
    43  // TODO(bar) install dns resolver in init(){}.
    44  
    45  // Register registers the resolver builder to the resolver map. b.Scheme will
    46  // be used as the scheme registered with this builder. The registry is case
    47  // sensitive, and schemes should not contain any uppercase characters.
    48  //
    49  // NOTE: this function must only be called during initialization time (i.e. in
    50  // an init() function), and is not thread-safe. If multiple Resolvers are
    51  // registered with the same name, the one registered last will take effect.
    52  func Register(b Builder) {
    53  	m[b.Scheme()] = b
    54  }
    55  
    56  // Get returns the resolver builder registered with the given scheme.
    57  //
    58  // If no builder is register with the scheme, nil will be returned.
    59  func Get(scheme string) Builder {
    60  	if b, ok := m[scheme]; ok {
    61  		return b
    62  	}
    63  	return nil
    64  }
    65  
    66  // SetDefaultScheme sets the default scheme that will be used. The default
    67  // scheme is initially set to "passthrough".
    68  //
    69  // NOTE: this function must only be called during initialization time (i.e. in
    70  // an init() function), and is not thread-safe. The scheme set last overrides
    71  // previously set values.
    72  func SetDefaultScheme(scheme string) {
    73  	defaultScheme = scheme
    74  	internal.UserSetDefaultScheme = true
    75  }
    76  
    77  // GetDefaultScheme gets the default scheme that will be used by grpc.Dial.  If
    78  // SetDefaultScheme is never called, the default scheme used by grpc.NewClient is "dns" instead.
    79  func GetDefaultScheme() string {
    80  	return defaultScheme
    81  }
    82  
    83  // Address represents a server the client connects to.
    84  //
    85  // # Experimental
    86  //
    87  // Notice: This type is EXPERIMENTAL and may be changed or removed in a
    88  // later release.
    89  type Address struct {
    90  	// Addr is the server address on which a connection will be established.
    91  	Addr string
    92  
    93  	// ServerName is the name of this address.
    94  	// If non-empty, the ServerName is used as the transport certification authority for
    95  	// the address, instead of the hostname from the Dial target string. In most cases,
    96  	// this should not be set.
    97  	//
    98  	// WARNING: ServerName must only be populated with trusted values. It
    99  	// is insecure to populate it with data from untrusted inputs since untrusted
   100  	// values could be used to bypass the authority checks performed by TLS.
   101  	ServerName string
   102  
   103  	// Attributes contains arbitrary data about this address intended for
   104  	// consumption by the SubConn.
   105  	Attributes *attributes.Attributes
   106  
   107  	// BalancerAttributes contains arbitrary data about this address intended
   108  	// for consumption by the LB policy.  These attributes do not affect SubConn
   109  	// creation, connection establishment, handshaking, etc.
   110  	//
   111  	// Deprecated: when an Address is inside an Endpoint, this field should not
   112  	// be used, and it will eventually be removed entirely.
   113  	BalancerAttributes *attributes.Attributes
   114  
   115  	// Metadata is the information associated with Addr, which may be used
   116  	// to make load balancing decision.
   117  	//
   118  	// Deprecated: use Attributes instead.
   119  	Metadata any
   120  }
   121  
   122  // Equal returns whether a and o are identical.  Metadata is compared directly,
   123  // not with any recursive introspection.
   124  //
   125  // This method compares all fields of the address. When used to tell apart
   126  // addresses during subchannel creation or connection establishment, it might be
   127  // more appropriate for the caller to implement custom equality logic.
   128  func (a Address) Equal(o Address) bool {
   129  	return a.Addr == o.Addr && a.ServerName == o.ServerName &&
   130  		a.Attributes.Equal(o.Attributes) &&
   131  		a.BalancerAttributes.Equal(o.BalancerAttributes) &&
   132  		a.Metadata == o.Metadata
   133  }
   134  
   135  // String returns JSON formatted string representation of the address.
   136  func (a Address) String() string {
   137  	var sb strings.Builder
   138  	sb.WriteString(fmt.Sprintf("{Addr: %q, ", a.Addr))
   139  	sb.WriteString(fmt.Sprintf("ServerName: %q, ", a.ServerName))
   140  	if a.Attributes != nil {
   141  		sb.WriteString(fmt.Sprintf("Attributes: %v, ", a.Attributes.String()))
   142  	}
   143  	if a.BalancerAttributes != nil {
   144  		sb.WriteString(fmt.Sprintf("BalancerAttributes: %v", a.BalancerAttributes.String()))
   145  	}
   146  	sb.WriteString("}")
   147  	return sb.String()
   148  }
   149  
   150  // BuildOptions includes additional information for the builder to create
   151  // the resolver.
   152  type BuildOptions struct {
   153  	// DisableServiceConfig indicates whether a resolver implementation should
   154  	// fetch service config data.
   155  	DisableServiceConfig bool
   156  	// DialCreds is the transport credentials used by the ClientConn for
   157  	// communicating with the target gRPC service (set via
   158  	// WithTransportCredentials). In cases where a name resolution service
   159  	// requires the same credentials, the resolver may use this field. In most
   160  	// cases though, it is not appropriate, and this field may be ignored.
   161  	DialCreds credentials.TransportCredentials
   162  	// CredsBundle is the credentials bundle used by the ClientConn for
   163  	// communicating with the target gRPC service (set via
   164  	// WithCredentialsBundle). In cases where a name resolution service
   165  	// requires the same credentials, the resolver may use this field. In most
   166  	// cases though, it is not appropriate, and this field may be ignored.
   167  	CredsBundle credentials.Bundle
   168  	// Dialer is the custom dialer used by the ClientConn for dialling the
   169  	// target gRPC service (set via WithDialer). In cases where a name
   170  	// resolution service requires the same dialer, the resolver may use this
   171  	// field. In most cases though, it is not appropriate, and this field may
   172  	// be ignored.
   173  	Dialer func(context.Context, string) (net.Conn, error)
   174  	// Authority is the effective authority of the clientconn for which the
   175  	// resolver is built.
   176  	Authority string
   177  }
   178  
   179  // An Endpoint is one network endpoint, or server, which may have multiple
   180  // addresses with which it can be accessed.
   181  type Endpoint struct {
   182  	// Addresses contains a list of addresses used to access this endpoint.
   183  	Addresses []Address
   184  
   185  	// Attributes contains arbitrary data about this endpoint intended for
   186  	// consumption by the LB policy.
   187  	Attributes *attributes.Attributes
   188  }
   189  
   190  // State contains the current Resolver state relevant to the ClientConn.
   191  type State struct {
   192  	// Addresses is the latest set of resolved addresses for the target.
   193  	//
   194  	// If a resolver sets Addresses but does not set Endpoints, one Endpoint
   195  	// will be created for each Address before the State is passed to the LB
   196  	// policy.  The BalancerAttributes of each entry in Addresses will be set
   197  	// in Endpoints.Attributes, and be cleared in the Endpoint's Address's
   198  	// BalancerAttributes.
   199  	//
   200  	// Soon, Addresses will be deprecated and replaced fully by Endpoints.
   201  	Addresses []Address
   202  
   203  	// Endpoints is the latest set of resolved endpoints for the target.
   204  	//
   205  	// If a resolver produces a State containing Endpoints but not Addresses,
   206  	// it must take care to ensure the LB policies it selects will support
   207  	// Endpoints.
   208  	Endpoints []Endpoint
   209  
   210  	// ServiceConfig contains the result from parsing the latest service
   211  	// config.  If it is nil, it indicates no service config is present or the
   212  	// resolver does not provide service configs.
   213  	ServiceConfig *serviceconfig.ParseResult
   214  
   215  	// Attributes contains arbitrary data about the resolver intended for
   216  	// consumption by the load balancing policy.
   217  	Attributes *attributes.Attributes
   218  }
   219  
   220  // ClientConn contains the callbacks for resolver to notify any updates
   221  // to the gRPC ClientConn.
   222  //
   223  // This interface is to be implemented by gRPC. Users should not need a
   224  // brand new implementation of this interface. For the situations like
   225  // testing, the new implementation should embed this interface. This allows
   226  // gRPC to add new methods to this interface.
   227  type ClientConn interface {
   228  	// UpdateState updates the state of the ClientConn appropriately.
   229  	//
   230  	// If an error is returned, the resolver should try to resolve the
   231  	// target again. The resolver should use a backoff timer to prevent
   232  	// overloading the server with requests. If a resolver is certain that
   233  	// reresolving will not change the result, e.g. because it is
   234  	// a watch-based resolver, returned errors can be ignored.
   235  	//
   236  	// If the resolved State is the same as the last reported one, calling
   237  	// UpdateState can be omitted.
   238  	UpdateState(State) error
   239  	// ReportError notifies the ClientConn that the Resolver encountered an
   240  	// error.  The ClientConn will notify the load balancer and begin calling
   241  	// ResolveNow on the Resolver with exponential backoff.
   242  	ReportError(error)
   243  	// NewAddress is called by resolver to notify ClientConn a new list
   244  	// of resolved addresses.
   245  	// The address list should be the complete list of resolved addresses.
   246  	//
   247  	// Deprecated: Use UpdateState instead.
   248  	NewAddress(addresses []Address)
   249  	// ParseServiceConfig parses the provided service config and returns an
   250  	// object that provides the parsed config.
   251  	ParseServiceConfig(serviceConfigJSON string) *serviceconfig.ParseResult
   252  }
   253  
   254  // Target represents a target for gRPC, as specified in:
   255  // https://github.com/grpc/grpc/blob/master/doc/naming.md.
   256  // It is parsed from the target string that gets passed into Dial or DialContext
   257  // by the user. And gRPC passes it to the resolver and the balancer.
   258  //
   259  // If the target follows the naming spec, and the parsed scheme is registered
   260  // with gRPC, we will parse the target string according to the spec. If the
   261  // target does not contain a scheme or if the parsed scheme is not registered
   262  // (i.e. no corresponding resolver available to resolve the endpoint), we will
   263  // apply the default scheme, and will attempt to reparse it.
   264  type Target struct {
   265  	// URL contains the parsed dial target with an optional default scheme added
   266  	// to it if the original dial target contained no scheme or contained an
   267  	// unregistered scheme. Any query params specified in the original dial
   268  	// target can be accessed from here.
   269  	URL url.URL
   270  }
   271  
   272  // Endpoint retrieves endpoint without leading "/" from either `URL.Path`
   273  // or `URL.Opaque`. The latter is used when the former is empty.
   274  func (t Target) Endpoint() string {
   275  	endpoint := t.URL.Path
   276  	if endpoint == "" {
   277  		endpoint = t.URL.Opaque
   278  	}
   279  	// For targets of the form "[scheme]://[authority]/endpoint, the endpoint
   280  	// value returned from url.Parse() contains a leading "/". Although this is
   281  	// in accordance with RFC 3986, we do not want to break existing resolver
   282  	// implementations which expect the endpoint without the leading "/". So, we
   283  	// end up stripping the leading "/" here. But this will result in an
   284  	// incorrect parsing for something like "unix:///path/to/socket". Since we
   285  	// own the "unix" resolver, we can workaround in the unix resolver by using
   286  	// the `URL` field.
   287  	return strings.TrimPrefix(endpoint, "/")
   288  }
   289  
   290  // String returns the canonical string representation of Target.
   291  func (t Target) String() string {
   292  	return t.URL.Scheme + "://" + t.URL.Host + "/" + t.Endpoint()
   293  }
   294  
   295  // Builder creates a resolver that will be used to watch name resolution updates.
   296  type Builder interface {
   297  	// Build creates a new resolver for the given target.
   298  	//
   299  	// gRPC dial calls Build synchronously, and fails if the returned error is
   300  	// not nil.
   301  	Build(target Target, cc ClientConn, opts BuildOptions) (Resolver, error)
   302  	// Scheme returns the scheme supported by this resolver.  Scheme is defined
   303  	// at https://github.com/grpc/grpc/blob/master/doc/naming.md.  The returned
   304  	// string should not contain uppercase characters, as they will not match
   305  	// the parsed target's scheme as defined in RFC 3986.
   306  	Scheme() string
   307  }
   308  
   309  // ResolveNowOptions includes additional information for ResolveNow.
   310  type ResolveNowOptions struct{}
   311  
   312  // Resolver watches for the updates on the specified target.
   313  // Updates include address updates and service config updates.
   314  type Resolver interface {
   315  	// ResolveNow will be called by gRPC to try to resolve the target name
   316  	// again. It's just a hint, resolver can ignore this if it's not necessary.
   317  	//
   318  	// It could be called multiple times concurrently.
   319  	ResolveNow(ResolveNowOptions)
   320  	// Close closes the resolver.
   321  	Close()
   322  }
   323  
   324  // AuthorityOverrider is implemented by Builders that wish to override the
   325  // default authority for the ClientConn.
   326  // By default, the authority used is target.Endpoint().
   327  type AuthorityOverrider interface {
   328  	// OverrideAuthority returns the authority to use for a ClientConn with the
   329  	// given target. The implementation must generate it without blocking,
   330  	// typically in line, and must keep it unchanged.
   331  	OverrideAuthority(Target) string
   332  }
   333  

View as plain text