balancer.go 5.0 KB

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