balancer.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. // pinAddr is the currently pinned address; set to the empty string on
  39. // intialization and shutdown.
  40. pinAddr string
  41. closed bool
  42. }
  43. func newSimpleBalancer(eps []string) *simpleBalancer {
  44. notifyCh := make(chan []grpc.Address, 1)
  45. addrs := make([]grpc.Address, len(eps))
  46. for i := range eps {
  47. addrs[i].Addr = getHost(eps[i])
  48. }
  49. notifyCh <- addrs
  50. sb := &simpleBalancer{
  51. addrs: addrs,
  52. notifyCh: notifyCh,
  53. readyc: make(chan struct{}),
  54. upEps: make(map[string]struct{}),
  55. upc: make(chan struct{}),
  56. }
  57. return sb
  58. }
  59. func (b *simpleBalancer) Start(target string) error { return nil }
  60. func (b *simpleBalancer) ConnectNotify() <-chan struct{} {
  61. b.mu.Lock()
  62. defer b.mu.Unlock()
  63. return b.upc
  64. }
  65. func (b *simpleBalancer) Up(addr grpc.Address) func(error) {
  66. b.mu.Lock()
  67. defer b.mu.Unlock()
  68. // gRPC might call Up after it called Close. We add this check
  69. // to "fix" it up at application layer. Or our simplerBalancer
  70. // might panic since b.upc is closed.
  71. if b.closed {
  72. return func(err error) {}
  73. }
  74. if len(b.upEps) == 0 {
  75. // notify waiting Get()s and pin first connected address
  76. close(b.upc)
  77. b.pinAddr = addr.Addr
  78. }
  79. b.upEps[addr.Addr] = struct{}{}
  80. // notify client that a connection is up
  81. b.readyOnce.Do(func() { close(b.readyc) })
  82. return func(err error) {
  83. b.mu.Lock()
  84. delete(b.upEps, addr.Addr)
  85. if len(b.upEps) == 0 && b.pinAddr != "" {
  86. b.upc = make(chan struct{})
  87. } else if b.pinAddr == addr.Addr {
  88. // choose new random up endpoint
  89. for k := range b.upEps {
  90. b.pinAddr = k
  91. break
  92. }
  93. }
  94. b.mu.Unlock()
  95. }
  96. }
  97. func (b *simpleBalancer) Get(ctx context.Context, opts grpc.BalancerGetOptions) (grpc.Address, func(), error) {
  98. var addr string
  99. for {
  100. b.mu.RLock()
  101. ch := b.upc
  102. b.mu.RUnlock()
  103. select {
  104. case <-ch:
  105. case <-ctx.Done():
  106. return grpc.Address{Addr: ""}, nil, ctx.Err()
  107. }
  108. b.mu.RLock()
  109. addr = b.pinAddr
  110. upEps := len(b.upEps)
  111. b.mu.RUnlock()
  112. if addr == "" {
  113. return grpc.Address{Addr: ""}, nil, grpc.ErrClientConnClosing
  114. }
  115. if upEps > 0 {
  116. break
  117. }
  118. }
  119. return grpc.Address{Addr: addr}, func() {}, nil
  120. }
  121. func (b *simpleBalancer) Notify() <-chan []grpc.Address { return b.notifyCh }
  122. func (b *simpleBalancer) Close() error {
  123. b.mu.Lock()
  124. defer b.mu.Unlock()
  125. // In case gRPC calls close twice. TODO: remove the checking
  126. // when we are sure that gRPC wont call close twice.
  127. if b.closed {
  128. return nil
  129. }
  130. b.closed = true
  131. close(b.notifyCh)
  132. // terminate all waiting Get()s
  133. b.pinAddr = ""
  134. if len(b.upEps) == 0 {
  135. close(b.upc)
  136. }
  137. return nil
  138. }
  139. func getHost(ep string) string {
  140. url, uerr := url.Parse(ep)
  141. if uerr != nil || !strings.Contains(ep, "://") {
  142. return ep
  143. }
  144. return url.Host
  145. }