balancer.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. // Copyright 2016 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 clientv3
  15. import (
  16. "net/url"
  17. "strings"
  18. "sync"
  19. "golang.org/x/net/context"
  20. "google.golang.org/grpc"
  21. "google.golang.org/grpc/codes"
  22. )
  23. // ErrNoAddrAvilable is returned by Get() when the balancer does not have
  24. // any active connection to endpoints at the time.
  25. // This error is returned only when opts.BlockingWait is true.
  26. var ErrNoAddrAvilable = grpc.Errorf(codes.Unavailable, "there is no address available")
  27. // simpleBalancer does the bare minimum to expose multiple eps
  28. // to the grpc reconnection code path
  29. type simpleBalancer struct {
  30. // addrs are the client's endpoints for grpc
  31. addrs []grpc.Address
  32. // notifyCh notifies grpc of the set of addresses for connecting
  33. notifyCh chan []grpc.Address
  34. // readyc closes once the first connection is up
  35. readyc chan struct{}
  36. readyOnce sync.Once
  37. // mu protects upEps, pinAddr, and connectingAddr
  38. mu sync.RWMutex
  39. // upEps holds the current endpoints that have an active connection
  40. upEps map[string]struct{}
  41. // upc closes when upEps transitions from empty to non-zero or the balancer closes.
  42. upc chan struct{}
  43. // grpc issues TLS cert checks using the string passed into dial so
  44. // that string must be the host. To recover the full scheme://host URL,
  45. // have a map from hosts to the original endpoint.
  46. host2ep map[string]string
  47. // pinAddr is the currently pinned address; set to the empty string on
  48. // intialization and shutdown.
  49. pinAddr string
  50. closed bool
  51. }
  52. func newSimpleBalancer(eps []string) *simpleBalancer {
  53. notifyCh := make(chan []grpc.Address, 1)
  54. addrs := make([]grpc.Address, len(eps))
  55. for i := range eps {
  56. addrs[i].Addr = getHost(eps[i])
  57. }
  58. notifyCh <- addrs
  59. sb := &simpleBalancer{
  60. addrs: addrs,
  61. notifyCh: notifyCh,
  62. readyc: make(chan struct{}),
  63. upEps: make(map[string]struct{}),
  64. upc: make(chan struct{}),
  65. host2ep: getHost2ep(eps),
  66. }
  67. return sb
  68. }
  69. func (b *simpleBalancer) Start(target string, config grpc.BalancerConfig) error { return nil }
  70. func (b *simpleBalancer) ConnectNotify() <-chan struct{} {
  71. b.mu.Lock()
  72. defer b.mu.Unlock()
  73. return b.upc
  74. }
  75. func (b *simpleBalancer) getEndpoint(host string) string {
  76. b.mu.Lock()
  77. defer b.mu.Unlock()
  78. return b.host2ep[host]
  79. }
  80. func getHost2ep(eps []string) map[string]string {
  81. hm := make(map[string]string, len(eps))
  82. for i := range eps {
  83. _, host, _ := parseEndpoint(eps[i])
  84. hm[host] = eps[i]
  85. }
  86. return hm
  87. }
  88. func (b *simpleBalancer) updateAddrs(eps []string) {
  89. np := getHost2ep(eps)
  90. b.mu.Lock()
  91. defer b.mu.Unlock()
  92. match := len(np) == len(b.host2ep)
  93. for k, v := range np {
  94. if b.host2ep[k] != v {
  95. match = false
  96. break
  97. }
  98. }
  99. if match {
  100. // same endpoints, so no need to update address
  101. return
  102. }
  103. b.host2ep = np
  104. addrs := make([]grpc.Address, 0, len(eps))
  105. for i := range eps {
  106. addrs = append(addrs, grpc.Address{Addr: getHost(eps[i])})
  107. }
  108. b.addrs = addrs
  109. b.notifyCh <- addrs
  110. }
  111. func (b *simpleBalancer) Up(addr grpc.Address) func(error) {
  112. b.mu.Lock()
  113. defer b.mu.Unlock()
  114. // gRPC might call Up after it called Close. We add this check
  115. // to "fix" it up at application layer. Or our simplerBalancer
  116. // might panic since b.upc is closed.
  117. if b.closed {
  118. return func(err error) {}
  119. }
  120. if len(b.upEps) == 0 {
  121. // notify waiting Get()s and pin first connected address
  122. close(b.upc)
  123. b.pinAddr = addr.Addr
  124. }
  125. b.upEps[addr.Addr] = struct{}{}
  126. // notify client that a connection is up
  127. b.readyOnce.Do(func() { close(b.readyc) })
  128. return func(err error) {
  129. b.mu.Lock()
  130. delete(b.upEps, addr.Addr)
  131. if len(b.upEps) == 0 && b.pinAddr != "" {
  132. b.upc = make(chan struct{})
  133. } else if b.pinAddr == addr.Addr {
  134. // choose new random up endpoint
  135. for k := range b.upEps {
  136. b.pinAddr = k
  137. break
  138. }
  139. }
  140. b.mu.Unlock()
  141. }
  142. }
  143. func (b *simpleBalancer) Get(ctx context.Context, opts grpc.BalancerGetOptions) (grpc.Address, func(), error) {
  144. var addr string
  145. // If opts.BlockingWait is false (for fail-fast RPCs), it should return
  146. // an address it has notified via Notify immediately instead of blocking.
  147. if !opts.BlockingWait {
  148. b.mu.RLock()
  149. closed := b.closed
  150. addr = b.pinAddr
  151. upEps := len(b.upEps)
  152. b.mu.RUnlock()
  153. if closed {
  154. return grpc.Address{Addr: ""}, nil, grpc.ErrClientConnClosing
  155. }
  156. if upEps == 0 {
  157. return grpc.Address{Addr: ""}, nil, ErrNoAddrAvilable
  158. }
  159. return grpc.Address{Addr: addr}, func() {}, nil
  160. }
  161. for {
  162. b.mu.RLock()
  163. ch := b.upc
  164. b.mu.RUnlock()
  165. select {
  166. case <-ch:
  167. case <-ctx.Done():
  168. return grpc.Address{Addr: ""}, nil, ctx.Err()
  169. }
  170. b.mu.RLock()
  171. addr = b.pinAddr
  172. upEps := len(b.upEps)
  173. b.mu.RUnlock()
  174. if addr == "" {
  175. return grpc.Address{Addr: ""}, nil, grpc.ErrClientConnClosing
  176. }
  177. if upEps > 0 {
  178. break
  179. }
  180. }
  181. return grpc.Address{Addr: addr}, func() {}, nil
  182. }
  183. func (b *simpleBalancer) Notify() <-chan []grpc.Address { return b.notifyCh }
  184. func (b *simpleBalancer) Close() error {
  185. b.mu.Lock()
  186. defer b.mu.Unlock()
  187. // In case gRPC calls close twice. TODO: remove the checking
  188. // when we are sure that gRPC wont call close twice.
  189. if b.closed {
  190. return nil
  191. }
  192. b.closed = true
  193. close(b.notifyCh)
  194. // terminate all waiting Get()s
  195. b.pinAddr = ""
  196. if len(b.upEps) == 0 {
  197. close(b.upc)
  198. }
  199. return nil
  200. }
  201. func getHost(ep string) string {
  202. url, uerr := url.Parse(ep)
  203. if uerr != nil || !strings.Contains(ep, "://") {
  204. return ep
  205. }
  206. return url.Host
  207. }