balancer.go 8.1 KB

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