resolver.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. // AddressType indicates the address type returned by name resolution.
  71. //
  72. // Deprecated: use Attributes in Address instead.
  73. type AddressType uint8
  74. const (
  75. // Backend indicates the address is for a backend server.
  76. //
  77. // Deprecated: use Attributes in Address instead.
  78. Backend AddressType = iota
  79. // GRPCLB indicates the address is for a grpclb load balancer.
  80. //
  81. // Deprecated: to select the GRPCLB load balancing policy, use a service
  82. // config with a corresponding loadBalancingConfig. To supply balancer
  83. // addresses to the GRPCLB load balancing policy, set State.Attributes
  84. // using balancer/grpclb/state.Set.
  85. GRPCLB
  86. )
  87. // Address represents a server the client connects to.
  88. //
  89. // # Experimental
  90. //
  91. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  92. // later release.
  93. type Address struct {
  94. // Addr is the server address on which a connection will be established.
  95. Addr string
  96. // ServerName is the name of this address.
  97. // If non-empty, the ServerName is used as the transport certification authority for
  98. // the address, instead of the hostname from the Dial target string. In most cases,
  99. // this should not be set.
  100. //
  101. // If Type is GRPCLB, ServerName should be the name of the remote load
  102. // balancer, not the name of the backend.
  103. //
  104. // WARNING: ServerName must only be populated with trusted values. It
  105. // is insecure to populate it with data from untrusted inputs since untrusted
  106. // values could be used to bypass the authority checks performed by TLS.
  107. ServerName string
  108. // Attributes contains arbitrary data about this address intended for
  109. // consumption by the SubConn.
  110. Attributes *attributes.Attributes
  111. // BalancerAttributes contains arbitrary data about this address intended
  112. // for consumption by the LB policy. These attributes do not affect SubConn
  113. // creation, connection establishment, handshaking, etc.
  114. BalancerAttributes *attributes.Attributes
  115. // Type is the type of this address.
  116. //
  117. // Deprecated: use Attributes instead.
  118. Type AddressType
  119. // Metadata is the information associated with Addr, which may be used
  120. // to make load balancing decision.
  121. //
  122. // Deprecated: use Attributes instead.
  123. Metadata interface{}
  124. }
  125. // Equal returns whether a and o are identical. Metadata is compared directly,
  126. // not with any recursive introspection.
  127. func (a Address) Equal(o Address) bool {
  128. return a.Addr == o.Addr && a.ServerName == o.ServerName &&
  129. a.Attributes.Equal(o.Attributes) &&
  130. a.BalancerAttributes.Equal(o.BalancerAttributes) &&
  131. a.Type == o.Type && a.Metadata == o.Metadata
  132. }
  133. // String returns JSON formatted string representation of the address.
  134. func (a Address) String() string {
  135. var sb strings.Builder
  136. sb.WriteString(fmt.Sprintf("{Addr: %q, ", a.Addr))
  137. sb.WriteString(fmt.Sprintf("ServerName: %q, ", a.ServerName))
  138. if a.Attributes != nil {
  139. sb.WriteString(fmt.Sprintf("Attributes: %v, ", a.Attributes.String()))
  140. }
  141. if a.BalancerAttributes != nil {
  142. sb.WriteString(fmt.Sprintf("BalancerAttributes: %v", a.BalancerAttributes.String()))
  143. }
  144. sb.WriteString("}")
  145. return sb.String()
  146. }
  147. // BuildOptions includes additional information for the builder to create
  148. // the resolver.
  149. type BuildOptions struct {
  150. // DisableServiceConfig indicates whether a resolver implementation should
  151. // fetch service config data.
  152. DisableServiceConfig bool
  153. // DialCreds is the transport credentials used by the ClientConn for
  154. // communicating with the target gRPC service (set via
  155. // WithTransportCredentials). In cases where a name resolution service
  156. // requires the same credentials, the resolver may use this field. In most
  157. // cases though, it is not appropriate, and this field may be ignored.
  158. DialCreds credentials.TransportCredentials
  159. // CredsBundle is the credentials bundle used by the ClientConn for
  160. // communicating with the target gRPC service (set via
  161. // WithCredentialsBundle). In cases where a name resolution service
  162. // requires the same credentials, the resolver may use this field. In most
  163. // cases though, it is not appropriate, and this field may be ignored.
  164. CredsBundle credentials.Bundle
  165. // Dialer is the custom dialer used by the ClientConn for dialling the
  166. // target gRPC service (set via WithDialer). In cases where a name
  167. // resolution service requires the same dialer, the resolver may use this
  168. // field. In most cases though, it is not appropriate, and this field may
  169. // be ignored.
  170. Dialer func(context.Context, string) (net.Conn, error)
  171. }
  172. // State contains the current Resolver state relevant to the ClientConn.
  173. type State struct {
  174. // Addresses is the latest set of resolved addresses for the target.
  175. Addresses []Address
  176. // ServiceConfig contains the result from parsing the latest service
  177. // config. If it is nil, it indicates no service config is present or the
  178. // resolver does not provide service configs.
  179. ServiceConfig *serviceconfig.ParseResult
  180. // Attributes contains arbitrary data about the resolver intended for
  181. // consumption by the load balancing policy.
  182. Attributes *attributes.Attributes
  183. }
  184. // ClientConn contains the callbacks for resolver to notify any updates
  185. // to the gRPC ClientConn.
  186. //
  187. // This interface is to be implemented by gRPC. Users should not need a
  188. // brand new implementation of this interface. For the situations like
  189. // testing, the new implementation should embed this interface. This allows
  190. // gRPC to add new methods to this interface.
  191. type ClientConn interface {
  192. // UpdateState updates the state of the ClientConn appropriately.
  193. //
  194. // If an error is returned, the resolver should try to resolve the
  195. // target again. The resolver should use a backoff timer to prevent
  196. // overloading the server with requests. If a resolver is certain that
  197. // reresolving will not change the result, e.g. because it is
  198. // a watch-based resolver, returned errors can be ignored.
  199. //
  200. // If the resolved State is the same as the last reported one, calling
  201. // UpdateState can be omitted.
  202. UpdateState(State) error
  203. // ReportError notifies the ClientConn that the Resolver encountered an
  204. // error. The ClientConn will notify the load balancer and begin calling
  205. // ResolveNow on the Resolver with exponential backoff.
  206. ReportError(error)
  207. // NewAddress is called by resolver to notify ClientConn a new list
  208. // of resolved addresses.
  209. // The address list should be the complete list of resolved addresses.
  210. //
  211. // Deprecated: Use UpdateState instead.
  212. NewAddress(addresses []Address)
  213. // NewServiceConfig is called by resolver to notify ClientConn a new
  214. // service config. The service config should be provided as a json string.
  215. //
  216. // Deprecated: Use UpdateState instead.
  217. NewServiceConfig(serviceConfig string)
  218. // ParseServiceConfig parses the provided service config and returns an
  219. // object that provides the parsed config.
  220. ParseServiceConfig(serviceConfigJSON string) *serviceconfig.ParseResult
  221. }
  222. // Target represents a target for gRPC, as specified in:
  223. // https://github.com/grpc/grpc/blob/master/doc/naming.md.
  224. // It is parsed from the target string that gets passed into Dial or DialContext
  225. // by the user. And gRPC passes it to the resolver and the balancer.
  226. //
  227. // If the target follows the naming spec, and the parsed scheme is registered
  228. // with gRPC, we will parse the target string according to the spec. If the
  229. // target does not contain a scheme or if the parsed scheme is not registered
  230. // (i.e. no corresponding resolver available to resolve the endpoint), we will
  231. // apply the default scheme, and will attempt to reparse it.
  232. //
  233. // Examples:
  234. //
  235. // - "dns://some_authority/foo.bar"
  236. // Target{Scheme: "dns", Authority: "some_authority", Endpoint: "foo.bar"}
  237. // - "foo.bar"
  238. // Target{Scheme: resolver.GetDefaultScheme(), Endpoint: "foo.bar"}
  239. // - "unknown_scheme://authority/endpoint"
  240. // Target{Scheme: resolver.GetDefaultScheme(), Endpoint: "unknown_scheme://authority/endpoint"}
  241. type Target struct {
  242. // Deprecated: use URL.Scheme instead.
  243. Scheme string
  244. // Deprecated: use URL.Host instead.
  245. Authority string
  246. // URL contains the parsed dial target with an optional default scheme added
  247. // to it if the original dial target contained no scheme or contained an
  248. // unregistered scheme. Any query params specified in the original dial
  249. // target can be accessed from here.
  250. URL url.URL
  251. }
  252. // Endpoint retrieves endpoint without leading "/" from either `URL.Path`
  253. // or `URL.Opaque`. The latter is used when the former is empty.
  254. func (t Target) Endpoint() string {
  255. endpoint := t.URL.Path
  256. if endpoint == "" {
  257. endpoint = t.URL.Opaque
  258. }
  259. // For targets of the form "[scheme]://[authority]/endpoint, the endpoint
  260. // value returned from url.Parse() contains a leading "/". Although this is
  261. // in accordance with RFC 3986, we do not want to break existing resolver
  262. // implementations which expect the endpoint without the leading "/". So, we
  263. // end up stripping the leading "/" here. But this will result in an
  264. // incorrect parsing for something like "unix:///path/to/socket". Since we
  265. // own the "unix" resolver, we can workaround in the unix resolver by using
  266. // the `URL` field.
  267. return strings.TrimPrefix(endpoint, "/")
  268. }
  269. // Builder creates a resolver that will be used to watch name resolution updates.
  270. type Builder interface {
  271. // Build creates a new resolver for the given target.
  272. //
  273. // gRPC dial calls Build synchronously, and fails if the returned error is
  274. // not nil.
  275. Build(target Target, cc ClientConn, opts BuildOptions) (Resolver, error)
  276. // Scheme returns the scheme supported by this resolver. Scheme is defined
  277. // at https://github.com/grpc/grpc/blob/master/doc/naming.md. The returned
  278. // string should not contain uppercase characters, as they will not match
  279. // the parsed target's scheme as defined in RFC 3986.
  280. Scheme() string
  281. }
  282. // ResolveNowOptions includes additional information for ResolveNow.
  283. type ResolveNowOptions struct{}
  284. // Resolver watches for the updates on the specified target.
  285. // Updates include address updates and service config updates.
  286. type Resolver interface {
  287. // ResolveNow will be called by gRPC to try to resolve the target name
  288. // again. It's just a hint, resolver can ignore this if it's not necessary.
  289. //
  290. // It could be called multiple times concurrently.
  291. ResolveNow(ResolveNowOptions)
  292. // Close closes the resolver.
  293. Close()
  294. }
  295. // UnregisterForTesting removes the resolver builder with the given scheme from the
  296. // resolver map.
  297. // This function is for testing only.
  298. func UnregisterForTesting(scheme string) {
  299. delete(m, scheme)
  300. }