endpoint.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. // Copyright 2018 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package endpoint resolves etcd entpoints using grpc targets of the form 'endpoint://<id>/<endpoint>'.
  15. package endpoint
  16. import (
  17. "context"
  18. "fmt"
  19. "net"
  20. "net/url"
  21. "strings"
  22. "sync"
  23. "google.golang.org/grpc/resolver"
  24. )
  25. const scheme = "endpoint"
  26. var (
  27. targetPrefix = fmt.Sprintf("%s://", scheme)
  28. bldr *builder
  29. )
  30. func init() {
  31. bldr = &builder{
  32. resolverGroups: make(map[string]*ResolverGroup),
  33. }
  34. resolver.Register(bldr)
  35. }
  36. type builder struct {
  37. mu sync.RWMutex
  38. resolverGroups map[string]*ResolverGroup
  39. }
  40. // NewResolverGroup creates a new ResolverGroup with the given id.
  41. func NewResolverGroup(id string) (*ResolverGroup, error) {
  42. return bldr.newResolverGroup(id)
  43. }
  44. // ResolverGroup keeps all endpoints of resolvers using a common endpoint://<id>/ target
  45. // up-to-date.
  46. type ResolverGroup struct {
  47. mu sync.RWMutex
  48. id string
  49. endpoints []string
  50. resolvers []*Resolver
  51. }
  52. func (e *ResolverGroup) addResolver(r *Resolver) {
  53. e.mu.Lock()
  54. addrs := epsToAddrs(e.endpoints...)
  55. e.resolvers = append(e.resolvers, r)
  56. e.mu.Unlock()
  57. r.cc.NewAddress(addrs)
  58. }
  59. func (e *ResolverGroup) removeResolver(r *Resolver) {
  60. e.mu.Lock()
  61. for i, er := range e.resolvers {
  62. if er == r {
  63. e.resolvers = append(e.resolvers[:i], e.resolvers[i+1:]...)
  64. break
  65. }
  66. }
  67. e.mu.Unlock()
  68. }
  69. // SetEndpoints updates the endpoints for ResolverGroup. All registered resolver are updated
  70. // immediately with the new endpoints.
  71. func (e *ResolverGroup) SetEndpoints(endpoints []string) {
  72. addrs := epsToAddrs(endpoints...)
  73. e.mu.Lock()
  74. e.endpoints = endpoints
  75. for _, r := range e.resolvers {
  76. r.cc.NewAddress(addrs)
  77. }
  78. e.mu.Unlock()
  79. }
  80. // Target constructs a endpoint target using the endpoint id of the ResolverGroup.
  81. func (e *ResolverGroup) Target(endpoint string) string {
  82. return Target(e.id, endpoint)
  83. }
  84. // Target constructs a endpoint resolver target.
  85. func Target(id, endpoint string) string {
  86. return fmt.Sprintf("%s://%s/%s", scheme, id, endpoint)
  87. }
  88. // IsTarget checks if a given target string in an endpoint resolver target.
  89. func IsTarget(target string) bool {
  90. return strings.HasPrefix(target, "endpoint://")
  91. }
  92. func (e *ResolverGroup) Close() {
  93. bldr.close(e.id)
  94. }
  95. // Build creates or reuses an etcd resolver for the etcd cluster name identified by the authority part of the target.
  96. func (b *builder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOption) (resolver.Resolver, error) {
  97. if len(target.Authority) < 1 {
  98. return nil, fmt.Errorf("'etcd' target scheme requires non-empty authority identifying etcd cluster being routed to")
  99. }
  100. id := target.Authority
  101. es, err := b.getResolverGroup(id)
  102. if err != nil {
  103. return nil, fmt.Errorf("failed to build resolver: %v", err)
  104. }
  105. r := &Resolver{
  106. endpointID: id,
  107. cc: cc,
  108. }
  109. es.addResolver(r)
  110. return r, nil
  111. }
  112. func (b *builder) newResolverGroup(id string) (*ResolverGroup, error) {
  113. b.mu.RLock()
  114. _, ok := b.resolverGroups[id]
  115. b.mu.RUnlock()
  116. if ok {
  117. return nil, fmt.Errorf("Endpoint already exists for id: %s", id)
  118. }
  119. es := &ResolverGroup{id: id}
  120. b.mu.Lock()
  121. b.resolverGroups[id] = es
  122. b.mu.Unlock()
  123. return es, nil
  124. }
  125. func (b *builder) getResolverGroup(id string) (*ResolverGroup, error) {
  126. b.mu.RLock()
  127. es, ok := b.resolverGroups[id]
  128. b.mu.RUnlock()
  129. if !ok {
  130. return nil, fmt.Errorf("ResolverGroup not found for id: %s", id)
  131. }
  132. return es, nil
  133. }
  134. func (b *builder) close(id string) {
  135. b.mu.Lock()
  136. delete(b.resolverGroups, id)
  137. b.mu.Unlock()
  138. }
  139. func (b *builder) Scheme() string {
  140. return scheme
  141. }
  142. // Resolver provides a resolver for a single etcd cluster, identified by name.
  143. type Resolver struct {
  144. endpointID string
  145. cc resolver.ClientConn
  146. sync.RWMutex
  147. }
  148. // TODO: use balancer.epsToAddrs
  149. func epsToAddrs(eps ...string) (addrs []resolver.Address) {
  150. addrs = make([]resolver.Address, 0, len(eps))
  151. for _, ep := range eps {
  152. addrs = append(addrs, resolver.Address{Addr: ep})
  153. }
  154. return addrs
  155. }
  156. func (*Resolver) ResolveNow(o resolver.ResolveNowOption) {}
  157. func (r *Resolver) Close() {
  158. es, err := bldr.getResolverGroup(r.endpointID)
  159. if err != nil {
  160. return
  161. }
  162. es.removeResolver(r)
  163. }
  164. // ParseEndpoint endpoint parses an endpoint of the form
  165. // (http|https)://<host>*|(unix|unixs)://<path>)
  166. // and returns a protocol ('tcp' or 'unix'),
  167. // host (or filepath if a unix socket),
  168. // scheme (http, https, unix, unixs).
  169. func ParseEndpoint(endpoint string) (proto string, host string, scheme string) {
  170. proto = "tcp"
  171. host = endpoint
  172. url, uerr := url.Parse(endpoint)
  173. if uerr != nil || !strings.Contains(endpoint, "://") {
  174. return proto, host, scheme
  175. }
  176. scheme = url.Scheme
  177. // strip scheme:// prefix since grpc dials by host
  178. host = url.Host
  179. switch url.Scheme {
  180. case "http", "https":
  181. case "unix", "unixs":
  182. proto = "unix"
  183. host = url.Host + url.Path
  184. default:
  185. proto, host = "", ""
  186. }
  187. return proto, host, scheme
  188. }
  189. // ParseTarget parses a endpoint://<id>/<endpoint> string and returns the parsed id and endpoint.
  190. // If the target is malformed, an error is returned.
  191. func ParseTarget(target string) (string, string, error) {
  192. noPrefix := strings.TrimPrefix(target, targetPrefix)
  193. if noPrefix == target {
  194. return "", "", fmt.Errorf("malformed target, %s prefix is required: %s", targetPrefix, target)
  195. }
  196. parts := strings.SplitN(noPrefix, "/", 2)
  197. if len(parts) != 2 {
  198. return "", "", fmt.Errorf("malformed target, expected %s://<id>/<endpoint>, but got %s", scheme, target)
  199. }
  200. return parts[0], parts[1], nil
  201. }
  202. // Dialer dials a endpoint using net.Dialer.
  203. // Context cancelation and timeout are supported.
  204. func Dialer(ctx context.Context, dialEp string) (net.Conn, error) {
  205. proto, host, _ := ParseEndpoint(dialEp)
  206. select {
  207. case <-ctx.Done():
  208. return nil, ctx.Err()
  209. default:
  210. }
  211. dialer := &net.Dialer{}
  212. if deadline, ok := ctx.Deadline(); ok {
  213. dialer.Deadline = deadline
  214. }
  215. return dialer.DialContext(ctx, proto, host)
  216. }