balancer.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. "context"
  17. "net/url"
  18. "strings"
  19. "sync"
  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. type balancer interface {
  28. grpc.Balancer
  29. ConnectNotify() <-chan struct{}
  30. endpoint(host string) string
  31. endpoints() []string
  32. // up is Up but includes whether the balancer will use the connection.
  33. up(addr grpc.Address) (func(error), bool)
  34. // updateAddrs changes the balancer's endpoints.
  35. updateAddrs(endpoints ...string)
  36. // ready returns a channel that closes when the balancer first connects.
  37. ready() <-chan struct{}
  38. }
  39. // simpleBalancer does the bare minimum to expose multiple eps
  40. // to the grpc reconnection code path
  41. type simpleBalancer struct {
  42. // addrs are the client's endpoint addresses for grpc
  43. addrs []grpc.Address
  44. // eps holds the raw endpoints from the client
  45. eps []string
  46. // notifyCh notifies grpc of the set of addresses for connecting
  47. notifyCh chan []grpc.Address
  48. // readyc closes once the first connection is up
  49. readyc chan struct{}
  50. readyOnce sync.Once
  51. // mu protects all fields below.
  52. mu sync.RWMutex
  53. // upc closes when pinAddr transitions from empty to non-empty or the balancer closes.
  54. upc chan struct{}
  55. // downc closes when grpc calls down() on pinAddr
  56. downc chan struct{}
  57. // stopc is closed to signal updateNotifyLoop should stop.
  58. stopc chan struct{}
  59. // donec closes when all goroutines are exited
  60. donec chan struct{}
  61. // updateAddrsC notifies updateNotifyLoop to update addrs.
  62. updateAddrsC chan struct{}
  63. // grpc issues TLS cert checks using the string passed into dial so
  64. // that string must be the host. To recover the full scheme://host URL,
  65. // have a map from hosts to the original endpoint.
  66. host2ep map[string]string
  67. // pinAddr is the currently pinned address; set to the empty string on
  68. // initialization and shutdown.
  69. pinAddr string
  70. closed bool
  71. }
  72. func newSimpleBalancer(eps []string) *simpleBalancer {
  73. notifyCh := make(chan []grpc.Address, 1)
  74. addrs := eps2addrs(eps)
  75. sb := &simpleBalancer{
  76. addrs: addrs,
  77. eps: eps,
  78. notifyCh: notifyCh,
  79. readyc: make(chan struct{}),
  80. upc: make(chan struct{}),
  81. stopc: make(chan struct{}),
  82. downc: make(chan struct{}),
  83. donec: make(chan struct{}),
  84. updateAddrsC: make(chan struct{}, 1),
  85. host2ep: getHost2ep(eps),
  86. }
  87. close(sb.downc)
  88. go sb.updateNotifyLoop()
  89. return sb
  90. }
  91. func (b *simpleBalancer) Start(target string, config grpc.BalancerConfig) error { return nil }
  92. func (b *simpleBalancer) ConnectNotify() <-chan struct{} {
  93. b.mu.Lock()
  94. defer b.mu.Unlock()
  95. return b.upc
  96. }
  97. func (b *simpleBalancer) ready() <-chan struct{} { return b.readyc }
  98. func (b *simpleBalancer) endpoint(host string) string {
  99. b.mu.Lock()
  100. defer b.mu.Unlock()
  101. return b.host2ep[host]
  102. }
  103. func (b *simpleBalancer) endpoints() []string {
  104. b.mu.RLock()
  105. defer b.mu.RUnlock()
  106. return b.eps
  107. }
  108. func getHost2ep(eps []string) map[string]string {
  109. hm := make(map[string]string, len(eps))
  110. for i := range eps {
  111. _, host, _ := parseEndpoint(eps[i])
  112. hm[host] = eps[i]
  113. }
  114. return hm
  115. }
  116. func (b *simpleBalancer) updateAddrs(eps ...string) {
  117. np := getHost2ep(eps)
  118. b.mu.Lock()
  119. match := len(np) == len(b.host2ep)
  120. for k, v := range np {
  121. if b.host2ep[k] != v {
  122. match = false
  123. break
  124. }
  125. }
  126. if match {
  127. // same endpoints, so no need to update address
  128. b.mu.Unlock()
  129. return
  130. }
  131. b.host2ep = np
  132. b.addrs, b.eps = eps2addrs(eps), eps
  133. // updating notifyCh can trigger new connections,
  134. // only update addrs if all connections are down
  135. // or addrs does not include pinAddr.
  136. update := !hasAddr(b.addrs, b.pinAddr)
  137. b.mu.Unlock()
  138. if update {
  139. select {
  140. case b.updateAddrsC <- struct{}{}:
  141. case <-b.stopc:
  142. }
  143. }
  144. }
  145. func hasAddr(addrs []grpc.Address, targetAddr string) bool {
  146. for _, addr := range addrs {
  147. if targetAddr == addr.Addr {
  148. return true
  149. }
  150. }
  151. return false
  152. }
  153. func (b *simpleBalancer) updateNotifyLoop() {
  154. defer close(b.donec)
  155. for {
  156. b.mu.RLock()
  157. upc, downc, addr := b.upc, b.downc, b.pinAddr
  158. b.mu.RUnlock()
  159. // downc or upc should be closed
  160. select {
  161. case <-downc:
  162. downc = nil
  163. default:
  164. }
  165. select {
  166. case <-upc:
  167. upc = nil
  168. default:
  169. }
  170. switch {
  171. case downc == nil && upc == nil:
  172. // stale
  173. select {
  174. case <-b.stopc:
  175. return
  176. default:
  177. }
  178. case downc == nil:
  179. b.notifyAddrs()
  180. select {
  181. case <-upc:
  182. case <-b.updateAddrsC:
  183. b.notifyAddrs()
  184. case <-b.stopc:
  185. return
  186. }
  187. case upc == nil:
  188. select {
  189. // close connections that are not the pinned address
  190. case b.notifyCh <- []grpc.Address{{Addr: addr}}:
  191. case <-downc:
  192. case <-b.stopc:
  193. return
  194. }
  195. select {
  196. case <-downc:
  197. case <-b.updateAddrsC:
  198. case <-b.stopc:
  199. return
  200. }
  201. b.notifyAddrs()
  202. }
  203. }
  204. }
  205. func (b *simpleBalancer) notifyAddrs() {
  206. b.mu.RLock()
  207. addrs := b.addrs
  208. b.mu.RUnlock()
  209. select {
  210. case b.notifyCh <- addrs:
  211. case <-b.stopc:
  212. }
  213. }
  214. func (b *simpleBalancer) Up(addr grpc.Address) func(error) {
  215. f, _ := b.up(addr)
  216. return f
  217. }
  218. func (b *simpleBalancer) up(addr grpc.Address) (func(error), bool) {
  219. b.mu.Lock()
  220. defer b.mu.Unlock()
  221. // gRPC might call Up after it called Close. We add this check
  222. // to "fix" it up at application layer. Otherwise, will panic
  223. // if b.upc is already closed.
  224. if b.closed {
  225. return func(err error) {}, false
  226. }
  227. // gRPC might call Up on a stale address.
  228. // Prevent updating pinAddr with a stale address.
  229. if !hasAddr(b.addrs, addr.Addr) {
  230. return func(err error) {}, false
  231. }
  232. if b.pinAddr != "" {
  233. return func(err error) {}, false
  234. }
  235. // notify waiting Get()s and pin first connected address
  236. close(b.upc)
  237. b.downc = make(chan struct{})
  238. b.pinAddr = addr.Addr
  239. // notify client that a connection is up
  240. b.readyOnce.Do(func() { close(b.readyc) })
  241. return func(err error) {
  242. b.mu.Lock()
  243. b.upc = make(chan struct{})
  244. close(b.downc)
  245. b.pinAddr = ""
  246. b.mu.Unlock()
  247. }, true
  248. }
  249. func (b *simpleBalancer) Get(ctx context.Context, opts grpc.BalancerGetOptions) (grpc.Address, func(), error) {
  250. var (
  251. addr string
  252. closed bool
  253. )
  254. // If opts.BlockingWait is false (for fail-fast RPCs), it should return
  255. // an address it has notified via Notify immediately instead of blocking.
  256. if !opts.BlockingWait {
  257. b.mu.RLock()
  258. closed = b.closed
  259. addr = b.pinAddr
  260. b.mu.RUnlock()
  261. if closed {
  262. return grpc.Address{Addr: ""}, nil, grpc.ErrClientConnClosing
  263. }
  264. if addr == "" {
  265. return grpc.Address{Addr: ""}, nil, ErrNoAddrAvilable
  266. }
  267. return grpc.Address{Addr: addr}, func() {}, nil
  268. }
  269. for {
  270. b.mu.RLock()
  271. ch := b.upc
  272. b.mu.RUnlock()
  273. select {
  274. case <-ch:
  275. case <-b.donec:
  276. return grpc.Address{Addr: ""}, nil, grpc.ErrClientConnClosing
  277. case <-ctx.Done():
  278. return grpc.Address{Addr: ""}, nil, ctx.Err()
  279. }
  280. b.mu.RLock()
  281. closed = b.closed
  282. addr = b.pinAddr
  283. b.mu.RUnlock()
  284. // Close() which sets b.closed = true can be called before Get(), Get() must exit if balancer is closed.
  285. if closed {
  286. return grpc.Address{Addr: ""}, nil, grpc.ErrClientConnClosing
  287. }
  288. if addr != "" {
  289. break
  290. }
  291. }
  292. return grpc.Address{Addr: addr}, func() {}, nil
  293. }
  294. func (b *simpleBalancer) Notify() <-chan []grpc.Address { return b.notifyCh }
  295. func (b *simpleBalancer) Close() error {
  296. b.mu.Lock()
  297. // In case gRPC calls close twice. TODO: remove the checking
  298. // when we are sure that gRPC wont call close twice.
  299. if b.closed {
  300. b.mu.Unlock()
  301. <-b.donec
  302. return nil
  303. }
  304. b.closed = true
  305. close(b.stopc)
  306. b.pinAddr = ""
  307. // In the case of following scenario:
  308. // 1. upc is not closed; no pinned address
  309. // 2. client issues an RPC, calling invoke(), which calls Get(), enters for loop, blocks
  310. // 3. client.conn.Close() calls balancer.Close(); closed = true
  311. // 4. for loop in Get() never exits since ctx is the context passed in by the client and may not be canceled
  312. // we must close upc so Get() exits from blocking on upc
  313. select {
  314. case <-b.upc:
  315. default:
  316. // terminate all waiting Get()s
  317. close(b.upc)
  318. }
  319. b.mu.Unlock()
  320. // wait for updateNotifyLoop to finish
  321. <-b.donec
  322. close(b.notifyCh)
  323. return nil
  324. }
  325. func getHost(ep string) string {
  326. url, uerr := url.Parse(ep)
  327. if uerr != nil || !strings.Contains(ep, "://") {
  328. return ep
  329. }
  330. return url.Host
  331. }
  332. func eps2addrs(eps []string) []grpc.Address {
  333. addrs := make([]grpc.Address, len(eps))
  334. for i := range eps {
  335. addrs[i].Addr = getHost(eps[i])
  336. }
  337. return addrs
  338. }