balancer.go 7.4 KB

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