balancer.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. sb := &simpleBalancer{
  65. addrs: addrs,
  66. notifyCh: notifyCh,
  67. readyc: make(chan struct{}),
  68. upc: make(chan struct{}),
  69. stopc: make(chan struct{}),
  70. downc: make(chan struct{}),
  71. donec: make(chan struct{}),
  72. updateAddrsC: make(chan struct{}, 1),
  73. host2ep: getHost2ep(eps),
  74. }
  75. close(sb.downc)
  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, downc, addr := b.upc, b.downc, b.pinAddr
  144. b.mu.RUnlock()
  145. // downc or upc should be closed
  146. select {
  147. case <-downc:
  148. downc = nil
  149. default:
  150. }
  151. select {
  152. case <-upc:
  153. upc = nil
  154. default:
  155. }
  156. switch {
  157. case downc == nil && upc == nil:
  158. // stale
  159. select {
  160. case <-b.stopc:
  161. return
  162. default:
  163. }
  164. case downc == nil:
  165. b.notifyAddrs()
  166. select {
  167. case <-upc:
  168. case <-b.updateAddrsC:
  169. b.notifyAddrs()
  170. case <-b.stopc:
  171. return
  172. }
  173. case upc == nil:
  174. select {
  175. // close connections that are not the pinned address
  176. case b.notifyCh <- []grpc.Address{{Addr: addr}}:
  177. case <-downc:
  178. case <-b.stopc:
  179. return
  180. }
  181. select {
  182. case <-downc:
  183. case <-b.updateAddrsC:
  184. case <-b.stopc:
  185. return
  186. }
  187. b.notifyAddrs()
  188. }
  189. }
  190. }
  191. func (b *simpleBalancer) notifyAddrs() {
  192. b.mu.RLock()
  193. addrs := b.addrs
  194. b.mu.RUnlock()
  195. select {
  196. case b.notifyCh <- addrs:
  197. case <-b.stopc:
  198. }
  199. }
  200. func (b *simpleBalancer) Up(addr grpc.Address) func(error) {
  201. b.mu.Lock()
  202. defer b.mu.Unlock()
  203. // gRPC might call Up after it called Close. We add this check
  204. // to "fix" it up at application layer. Or our simplerBalancer
  205. // might panic since b.upc is closed.
  206. if b.closed {
  207. return func(err error) {}
  208. }
  209. // gRPC might call Up on a stale address.
  210. // Prevent updating pinAddr with a stale address.
  211. if !hasAddr(b.addrs, addr.Addr) {
  212. return func(err error) {}
  213. }
  214. if b.pinAddr != "" {
  215. return func(err error) {}
  216. }
  217. // notify waiting Get()s and pin first connected address
  218. close(b.upc)
  219. b.downc = make(chan struct{})
  220. b.pinAddr = addr.Addr
  221. // notify client that a connection is up
  222. b.readyOnce.Do(func() { close(b.readyc) })
  223. return func(err error) {
  224. b.mu.Lock()
  225. b.upc = make(chan struct{})
  226. close(b.downc)
  227. b.pinAddr = ""
  228. b.mu.Unlock()
  229. }
  230. }
  231. func (b *simpleBalancer) Get(ctx context.Context, opts grpc.BalancerGetOptions) (grpc.Address, func(), error) {
  232. var (
  233. addr string
  234. closed bool
  235. )
  236. // If opts.BlockingWait is false (for fail-fast RPCs), it should return
  237. // an address it has notified via Notify immediately instead of blocking.
  238. if !opts.BlockingWait {
  239. b.mu.RLock()
  240. closed = b.closed
  241. addr = b.pinAddr
  242. b.mu.RUnlock()
  243. if closed {
  244. return grpc.Address{Addr: ""}, nil, grpc.ErrClientConnClosing
  245. }
  246. if addr == "" {
  247. return grpc.Address{Addr: ""}, nil, ErrNoAddrAvilable
  248. }
  249. return grpc.Address{Addr: addr}, func() {}, nil
  250. }
  251. for {
  252. b.mu.RLock()
  253. ch := b.upc
  254. b.mu.RUnlock()
  255. select {
  256. case <-ch:
  257. case <-b.donec:
  258. return grpc.Address{Addr: ""}, nil, grpc.ErrClientConnClosing
  259. case <-ctx.Done():
  260. return grpc.Address{Addr: ""}, nil, ctx.Err()
  261. }
  262. b.mu.RLock()
  263. closed = b.closed
  264. addr = b.pinAddr
  265. b.mu.RUnlock()
  266. // Close() which sets b.closed = true can be called before Get(), Get() must exit if balancer is closed.
  267. if closed {
  268. return grpc.Address{Addr: ""}, nil, grpc.ErrClientConnClosing
  269. }
  270. if addr != "" {
  271. break
  272. }
  273. }
  274. return grpc.Address{Addr: addr}, func() {}, nil
  275. }
  276. func (b *simpleBalancer) Notify() <-chan []grpc.Address { return b.notifyCh }
  277. func (b *simpleBalancer) Close() error {
  278. b.mu.Lock()
  279. // In case gRPC calls close twice. TODO: remove the checking
  280. // when we are sure that gRPC wont call close twice.
  281. if b.closed {
  282. b.mu.Unlock()
  283. <-b.donec
  284. return nil
  285. }
  286. b.closed = true
  287. close(b.stopc)
  288. b.pinAddr = ""
  289. // In the case of following scenario:
  290. // 1. upc is not closed; no pinned address
  291. // 2. client issues an rpc, calling invoke(), which calls Get(), enters for loop, blocks
  292. // 3. clientconn.Close() calls balancer.Close(); closed = true
  293. // 4. for loop in Get() never exits since ctx is the context passed in by the client and may not be canceled
  294. // we must close upc so Get() exits from blocking on upc
  295. select {
  296. case <-b.upc:
  297. default:
  298. // terminate all waiting Get()s
  299. close(b.upc)
  300. }
  301. b.mu.Unlock()
  302. // wait for updateNotifyLoop to finish
  303. <-b.donec
  304. close(b.notifyCh)
  305. return nil
  306. }
  307. func getHost(ep string) string {
  308. url, uerr := url.Parse(ep)
  309. if uerr != nil || !strings.Contains(ep, "://") {
  310. return ep
  311. }
  312. return url.Host
  313. }