balancer.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. b.mu.Lock()
  85. defer b.mu.Unlock()
  86. b.host2ep = getHost2ep(eps)
  87. addrs := make([]grpc.Address, 0, len(eps))
  88. for i := range eps {
  89. addrs = append(addrs, grpc.Address{Addr: getHost(eps[i])})
  90. }
  91. b.addrs = addrs
  92. b.notifyCh <- addrs
  93. }
  94. func (b *simpleBalancer) Up(addr grpc.Address) func(error) {
  95. b.mu.Lock()
  96. defer b.mu.Unlock()
  97. // gRPC might call Up after it called Close. We add this check
  98. // to "fix" it up at application layer. Or our simplerBalancer
  99. // might panic since b.upc is closed.
  100. if b.closed {
  101. return func(err error) {}
  102. }
  103. if len(b.upEps) == 0 {
  104. // notify waiting Get()s and pin first connected address
  105. close(b.upc)
  106. b.pinAddr = addr.Addr
  107. }
  108. b.upEps[addr.Addr] = struct{}{}
  109. // notify client that a connection is up
  110. b.readyOnce.Do(func() { close(b.readyc) })
  111. return func(err error) {
  112. b.mu.Lock()
  113. delete(b.upEps, addr.Addr)
  114. if len(b.upEps) == 0 && b.pinAddr != "" {
  115. b.upc = make(chan struct{})
  116. } else if b.pinAddr == addr.Addr {
  117. // choose new random up endpoint
  118. for k := range b.upEps {
  119. b.pinAddr = k
  120. break
  121. }
  122. }
  123. b.mu.Unlock()
  124. }
  125. }
  126. func (b *simpleBalancer) Get(ctx context.Context, opts grpc.BalancerGetOptions) (grpc.Address, func(), error) {
  127. var addr string
  128. for {
  129. b.mu.RLock()
  130. ch := b.upc
  131. b.mu.RUnlock()
  132. select {
  133. case <-ch:
  134. case <-ctx.Done():
  135. return grpc.Address{Addr: ""}, nil, ctx.Err()
  136. }
  137. b.mu.RLock()
  138. addr = b.pinAddr
  139. upEps := len(b.upEps)
  140. b.mu.RUnlock()
  141. if addr == "" {
  142. return grpc.Address{Addr: ""}, nil, grpc.ErrClientConnClosing
  143. }
  144. if upEps > 0 {
  145. break
  146. }
  147. }
  148. return grpc.Address{Addr: addr}, func() {}, nil
  149. }
  150. func (b *simpleBalancer) Notify() <-chan []grpc.Address { return b.notifyCh }
  151. func (b *simpleBalancer) Close() error {
  152. b.mu.Lock()
  153. defer b.mu.Unlock()
  154. // In case gRPC calls close twice. TODO: remove the checking
  155. // when we are sure that gRPC wont call close twice.
  156. if b.closed {
  157. return nil
  158. }
  159. b.closed = true
  160. close(b.notifyCh)
  161. // terminate all waiting Get()s
  162. b.pinAddr = ""
  163. if len(b.upEps) == 0 {
  164. close(b.upc)
  165. }
  166. return nil
  167. }
  168. func getHost(ep string) string {
  169. url, uerr := url.Parse(ep)
  170. if uerr != nil || !strings.Contains(ep, "://") {
  171. return ep
  172. }
  173. return url.Host
  174. }