balancer.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. // upc closes when upEps transitions from empty to non-zero or the balancer closes.
  40. upc chan struct{}
  41. // grpc issues TLS cert checks using the string passed into dial so
  42. // that string must be the host. To recover the full scheme://host URL,
  43. // have a map from hosts to the original endpoint.
  44. host2ep map[string]string
  45. // pinAddr is the currently pinned address; set to the empty string on
  46. // intialization and shutdown.
  47. pinAddr string
  48. closed bool
  49. }
  50. func newSimpleBalancer(eps []string) *simpleBalancer {
  51. notifyCh := make(chan []grpc.Address, 1)
  52. addrs := make([]grpc.Address, len(eps))
  53. for i := range eps {
  54. addrs[i].Addr = getHost(eps[i])
  55. }
  56. notifyCh <- addrs
  57. sb := &simpleBalancer{
  58. addrs: addrs,
  59. notifyCh: notifyCh,
  60. readyc: make(chan struct{}),
  61. upc: make(chan struct{}),
  62. host2ep: getHost2ep(eps),
  63. }
  64. return sb
  65. }
  66. func (b *simpleBalancer) Start(target string, config grpc.BalancerConfig) error { return nil }
  67. func (b *simpleBalancer) ConnectNotify() <-chan struct{} {
  68. b.mu.Lock()
  69. defer b.mu.Unlock()
  70. return b.upc
  71. }
  72. func (b *simpleBalancer) getEndpoint(host string) string {
  73. b.mu.Lock()
  74. defer b.mu.Unlock()
  75. return b.host2ep[host]
  76. }
  77. func getHost2ep(eps []string) map[string]string {
  78. hm := make(map[string]string, len(eps))
  79. for i := range eps {
  80. _, host, _ := parseEndpoint(eps[i])
  81. hm[host] = eps[i]
  82. }
  83. return hm
  84. }
  85. func (b *simpleBalancer) updateAddrs(eps []string) {
  86. np := getHost2ep(eps)
  87. b.mu.Lock()
  88. defer b.mu.Unlock()
  89. match := len(np) == len(b.host2ep)
  90. for k, v := range np {
  91. if b.host2ep[k] != v {
  92. match = false
  93. break
  94. }
  95. }
  96. if match {
  97. // same endpoints, so no need to update address
  98. return
  99. }
  100. b.host2ep = np
  101. addrs := make([]grpc.Address, 0, len(eps))
  102. for i := range eps {
  103. addrs = append(addrs, grpc.Address{Addr: getHost(eps[i])})
  104. }
  105. b.addrs = addrs
  106. // updating notifyCh can trigger new connections,
  107. // but balancer only expects new connections if all connections are down
  108. if b.pinAddr == "" {
  109. b.notifyCh <- addrs
  110. }
  111. }
  112. func (b *simpleBalancer) Up(addr grpc.Address) func(error) {
  113. b.mu.Lock()
  114. defer b.mu.Unlock()
  115. // gRPC might call Up after it called Close. We add this check
  116. // to "fix" it up at application layer. Or our simplerBalancer
  117. // might panic since b.upc is closed.
  118. if b.closed {
  119. return func(err error) {}
  120. }
  121. if b.pinAddr == "" {
  122. // notify waiting Get()s and pin first connected address
  123. close(b.upc)
  124. b.pinAddr = addr.Addr
  125. // notify client that a connection is up
  126. b.readyOnce.Do(func() { close(b.readyc) })
  127. // close opened connections that are not pinAddr
  128. // this ensures only one connection is open per client
  129. b.notifyCh <- []grpc.Address{addr}
  130. }
  131. return func(err error) {
  132. b.mu.Lock()
  133. if b.pinAddr == addr.Addr {
  134. b.upc = make(chan struct{})
  135. b.pinAddr = ""
  136. b.notifyCh <- b.addrs
  137. }
  138. b.mu.Unlock()
  139. }
  140. }
  141. func (b *simpleBalancer) Get(ctx context.Context, opts grpc.BalancerGetOptions) (grpc.Address, func(), error) {
  142. var (
  143. addr string
  144. closed bool
  145. )
  146. // If opts.BlockingWait is false (for fail-fast RPCs), it should return
  147. // an address it has notified via Notify immediately instead of blocking.
  148. if !opts.BlockingWait {
  149. b.mu.RLock()
  150. closed = b.closed
  151. addr = b.pinAddr
  152. b.mu.RUnlock()
  153. if closed {
  154. return grpc.Address{Addr: ""}, nil, grpc.ErrClientConnClosing
  155. }
  156. if addr == "" {
  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. closed = b.closed
  172. addr = b.pinAddr
  173. b.mu.RUnlock()
  174. // Close() which sets b.closed = true can be called before Get(), Get() must exit if balancer is closed.
  175. if closed {
  176. return grpc.Address{Addr: ""}, nil, grpc.ErrClientConnClosing
  177. }
  178. if addr != "" {
  179. break
  180. }
  181. }
  182. return grpc.Address{Addr: addr}, func() {}, nil
  183. }
  184. func (b *simpleBalancer) Notify() <-chan []grpc.Address { return b.notifyCh }
  185. func (b *simpleBalancer) Close() error {
  186. b.mu.Lock()
  187. defer b.mu.Unlock()
  188. // In case gRPC calls close twice. TODO: remove the checking
  189. // when we are sure that gRPC wont call close twice.
  190. if b.closed {
  191. return nil
  192. }
  193. b.closed = true
  194. close(b.notifyCh)
  195. b.pinAddr = ""
  196. // In the case of following scenario:
  197. // 1. upc is not closed; no pinned address
  198. // 2. client issues an rpc, calling invoke(), which calls Get(), enters for loop, blocks
  199. // 3. clientconn.Close() calls balancer.Close(); closed = true
  200. // 4. for loop in Get() never exits since ctx is the context passed in by the client and may not be canceled
  201. // we must close upc so Get() exits from blocking on upc
  202. select {
  203. case <-b.upc:
  204. default:
  205. // terminate all waiting Get()s
  206. close(b.upc)
  207. }
  208. return nil
  209. }
  210. func getHost(ep string) string {
  211. url, uerr := url.Parse(ep)
  212. if uerr != nil || !strings.Contains(ep, "://") {
  213. return ep
  214. }
  215. return url.Host
  216. }