resolver.go 12 KB

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