grpclb_util.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. /*
  2. *
  3. * Copyright 2016 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package grpclb
  19. import (
  20. "fmt"
  21. "sync"
  22. "time"
  23. "google.golang.org/grpc/balancer"
  24. "google.golang.org/grpc/connectivity"
  25. "google.golang.org/grpc/resolver"
  26. )
  27. // The parent ClientConn should re-resolve when grpclb loses connection to the
  28. // remote balancer. When the ClientConn inside grpclb gets a TransientFailure,
  29. // it calls lbManualResolver.ResolveNow(), which calls parent ClientConn's
  30. // ResolveNow, and eventually results in re-resolve happening in parent
  31. // ClientConn's resolver (DNS for example).
  32. //
  33. // parent
  34. // ClientConn
  35. // +-----------------------------------------------------------------+
  36. // | parent +---------------------------------+ |
  37. // | DNS ClientConn | grpclb | |
  38. // | resolver balancerWrapper | | |
  39. // | + + | grpclb grpclb | |
  40. // | | | | ManualResolver ClientConn | |
  41. // | | | | + + | |
  42. // | | | | | | Transient | |
  43. // | | | | | | Failure | |
  44. // | | | | | <--------- | | |
  45. // | | | <--------------- | ResolveNow | | |
  46. // | | <--------- | ResolveNow | | | | |
  47. // | | ResolveNow | | | | | |
  48. // | | | | | | | |
  49. // | + + | + + | |
  50. // | +---------------------------------+ |
  51. // +-----------------------------------------------------------------+
  52. // lbManualResolver is used by the ClientConn inside grpclb. It's a manual
  53. // resolver with a special ResolveNow() function.
  54. //
  55. // When ResolveNow() is called, it calls ResolveNow() on the parent ClientConn,
  56. // so when grpclb client lose contact with remote balancers, the parent
  57. // ClientConn's resolver will re-resolve.
  58. type lbManualResolver struct {
  59. scheme string
  60. ccr resolver.ClientConn
  61. ccb balancer.ClientConn
  62. }
  63. func (r *lbManualResolver) Build(_ resolver.Target, cc resolver.ClientConn, _ resolver.BuildOption) (resolver.Resolver, error) {
  64. r.ccr = cc
  65. return r, nil
  66. }
  67. func (r *lbManualResolver) Scheme() string {
  68. return r.scheme
  69. }
  70. // ResolveNow calls resolveNow on the parent ClientConn.
  71. func (r *lbManualResolver) ResolveNow(o resolver.ResolveNowOption) {
  72. r.ccb.ResolveNow(o)
  73. }
  74. // Close is a noop for Resolver.
  75. func (*lbManualResolver) Close() {}
  76. // UpdateState calls cc.UpdateState.
  77. func (r *lbManualResolver) UpdateState(s resolver.State) {
  78. r.ccr.UpdateState(s)
  79. }
  80. const subConnCacheTime = time.Second * 10
  81. // lbCacheClientConn is a wrapper balancer.ClientConn with a SubConn cache.
  82. // SubConns will be kept in cache for subConnCacheTime before being removed.
  83. //
  84. // Its new and remove methods are updated to do cache first.
  85. type lbCacheClientConn struct {
  86. cc balancer.ClientConn
  87. timeout time.Duration
  88. mu sync.Mutex
  89. // subConnCache only keeps subConns that are being deleted.
  90. subConnCache map[resolver.Address]*subConnCacheEntry
  91. subConnToAddr map[balancer.SubConn]resolver.Address
  92. }
  93. type subConnCacheEntry struct {
  94. sc balancer.SubConn
  95. cancel func()
  96. abortDeleting bool
  97. }
  98. func newLBCacheClientConn(cc balancer.ClientConn) *lbCacheClientConn {
  99. return &lbCacheClientConn{
  100. cc: cc,
  101. timeout: subConnCacheTime,
  102. subConnCache: make(map[resolver.Address]*subConnCacheEntry),
  103. subConnToAddr: make(map[balancer.SubConn]resolver.Address),
  104. }
  105. }
  106. func (ccc *lbCacheClientConn) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) {
  107. if len(addrs) != 1 {
  108. return nil, fmt.Errorf("grpclb calling NewSubConn with addrs of length %v", len(addrs))
  109. }
  110. addrWithoutMD := addrs[0]
  111. addrWithoutMD.Metadata = nil
  112. ccc.mu.Lock()
  113. defer ccc.mu.Unlock()
  114. if entry, ok := ccc.subConnCache[addrWithoutMD]; ok {
  115. // If entry is in subConnCache, the SubConn was being deleted.
  116. // cancel function will never be nil.
  117. entry.cancel()
  118. delete(ccc.subConnCache, addrWithoutMD)
  119. return entry.sc, nil
  120. }
  121. scNew, err := ccc.cc.NewSubConn(addrs, opts)
  122. if err != nil {
  123. return nil, err
  124. }
  125. ccc.subConnToAddr[scNew] = addrWithoutMD
  126. return scNew, nil
  127. }
  128. func (ccc *lbCacheClientConn) RemoveSubConn(sc balancer.SubConn) {
  129. ccc.mu.Lock()
  130. defer ccc.mu.Unlock()
  131. addr, ok := ccc.subConnToAddr[sc]
  132. if !ok {
  133. return
  134. }
  135. if entry, ok := ccc.subConnCache[addr]; ok {
  136. if entry.sc != sc {
  137. // This could happen if NewSubConn was called multiple times for the
  138. // same address, and those SubConns are all removed. We remove sc
  139. // immediately here.
  140. delete(ccc.subConnToAddr, sc)
  141. ccc.cc.RemoveSubConn(sc)
  142. }
  143. return
  144. }
  145. entry := &subConnCacheEntry{
  146. sc: sc,
  147. }
  148. ccc.subConnCache[addr] = entry
  149. timer := time.AfterFunc(ccc.timeout, func() {
  150. ccc.mu.Lock()
  151. if entry.abortDeleting {
  152. return
  153. }
  154. ccc.cc.RemoveSubConn(sc)
  155. delete(ccc.subConnToAddr, sc)
  156. delete(ccc.subConnCache, addr)
  157. ccc.mu.Unlock()
  158. })
  159. entry.cancel = func() {
  160. if !timer.Stop() {
  161. // If stop was not successful, the timer has fired (this can only
  162. // happen in a race). But the deleting function is blocked on ccc.mu
  163. // because the mutex was held by the caller of this function.
  164. //
  165. // Set abortDeleting to true to abort the deleting function. When
  166. // the lock is released, the deleting function will acquire the
  167. // lock, check the value of abortDeleting and return.
  168. entry.abortDeleting = true
  169. }
  170. }
  171. }
  172. func (ccc *lbCacheClientConn) UpdateBalancerState(s connectivity.State, p balancer.Picker) {
  173. ccc.cc.UpdateBalancerState(s, p)
  174. }
  175. func (ccc *lbCacheClientConn) close() {
  176. ccc.mu.Lock()
  177. // Only cancel all existing timers. There's no need to remove SubConns.
  178. for _, entry := range ccc.subConnCache {
  179. entry.cancel()
  180. }
  181. ccc.mu.Unlock()
  182. }