grpclb_util.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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/resolver"
  25. )
  26. // The parent ClientConn should re-resolve when grpclb loses connection to the
  27. // remote balancer. When the ClientConn inside grpclb gets a TransientFailure,
  28. // it calls lbManualResolver.ResolveNow(), which calls parent ClientConn's
  29. // ResolveNow, and eventually results in re-resolve happening in parent
  30. // ClientConn's resolver (DNS for example).
  31. //
  32. // parent
  33. // ClientConn
  34. // +-----------------------------------------------------------------+
  35. // | parent +---------------------------------+ |
  36. // | DNS ClientConn | grpclb | |
  37. // | resolver balancerWrapper | | |
  38. // | + + | grpclb grpclb | |
  39. // | | | | ManualResolver ClientConn | |
  40. // | | | | + + | |
  41. // | | | | | | Transient | |
  42. // | | | | | | Failure | |
  43. // | | | | | <--------- | | |
  44. // | | | <--------------- | ResolveNow | | |
  45. // | | <--------- | ResolveNow | | | | |
  46. // | | ResolveNow | | | | | |
  47. // | | | | | | | |
  48. // | + + | + + | |
  49. // | +---------------------------------+ |
  50. // +-----------------------------------------------------------------+
  51. // lbManualResolver is used by the ClientConn inside grpclb. It's a manual
  52. // resolver with a special ResolveNow() function.
  53. //
  54. // When ResolveNow() is called, it calls ResolveNow() on the parent ClientConn,
  55. // so when grpclb client lose contact with remote balancers, the parent
  56. // ClientConn's resolver will re-resolve.
  57. type lbManualResolver struct {
  58. scheme string
  59. ccr resolver.ClientConn
  60. ccb balancer.ClientConn
  61. }
  62. func (r *lbManualResolver) Build(_ resolver.Target, cc resolver.ClientConn, _ resolver.BuildOptions) (resolver.Resolver, error) {
  63. r.ccr = cc
  64. return r, nil
  65. }
  66. func (r *lbManualResolver) Scheme() string {
  67. return r.scheme
  68. }
  69. // ResolveNow calls resolveNow on the parent ClientConn.
  70. func (r *lbManualResolver) ResolveNow(o resolver.ResolveNowOptions) {
  71. r.ccb.ResolveNow(o)
  72. }
  73. // Close is a noop for Resolver.
  74. func (*lbManualResolver) Close() {}
  75. // UpdateState calls cc.UpdateState.
  76. func (r *lbManualResolver) UpdateState(s resolver.State) {
  77. r.ccr.UpdateState(s)
  78. }
  79. const subConnCacheTime = time.Second * 10
  80. // lbCacheClientConn is a wrapper balancer.ClientConn with a SubConn cache.
  81. // SubConns will be kept in cache for subConnCacheTime before being shut down.
  82. //
  83. // Its NewSubconn and SubConn.Shutdown methods are updated to do cache first.
  84. type lbCacheClientConn struct {
  85. balancer.ClientConn
  86. timeout time.Duration
  87. mu sync.Mutex
  88. // subConnCache only keeps subConns that are being deleted.
  89. subConnCache map[resolver.Address]*subConnCacheEntry
  90. subConnToAddr map[balancer.SubConn]resolver.Address
  91. }
  92. type subConnCacheEntry struct {
  93. sc balancer.SubConn
  94. cancel func()
  95. abortDeleting bool
  96. }
  97. func newLBCacheClientConn(cc balancer.ClientConn) *lbCacheClientConn {
  98. return &lbCacheClientConn{
  99. ClientConn: cc,
  100. timeout: subConnCacheTime,
  101. subConnCache: make(map[resolver.Address]*subConnCacheEntry),
  102. subConnToAddr: make(map[balancer.SubConn]resolver.Address),
  103. }
  104. }
  105. func (ccc *lbCacheClientConn) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) {
  106. if len(addrs) != 1 {
  107. return nil, fmt.Errorf("grpclb calling NewSubConn with addrs of length %v", len(addrs))
  108. }
  109. addrWithoutAttrs := addrs[0]
  110. addrWithoutAttrs.Attributes = nil
  111. ccc.mu.Lock()
  112. defer ccc.mu.Unlock()
  113. if entry, ok := ccc.subConnCache[addrWithoutAttrs]; ok {
  114. // If entry is in subConnCache, the SubConn was being deleted.
  115. // cancel function will never be nil.
  116. entry.cancel()
  117. delete(ccc.subConnCache, addrWithoutAttrs)
  118. return entry.sc, nil
  119. }
  120. scNew, err := ccc.ClientConn.NewSubConn(addrs, opts)
  121. if err != nil {
  122. return nil, err
  123. }
  124. scNew = &lbCacheSubConn{SubConn: scNew, ccc: ccc}
  125. ccc.subConnToAddr[scNew] = addrWithoutAttrs
  126. return scNew, nil
  127. }
  128. func (ccc *lbCacheClientConn) RemoveSubConn(sc balancer.SubConn) {
  129. logger.Errorf("RemoveSubConn(%v) called unexpectedly", sc)
  130. }
  131. type lbCacheSubConn struct {
  132. balancer.SubConn
  133. ccc *lbCacheClientConn
  134. }
  135. func (sc *lbCacheSubConn) Shutdown() {
  136. ccc := sc.ccc
  137. ccc.mu.Lock()
  138. defer ccc.mu.Unlock()
  139. addr, ok := ccc.subConnToAddr[sc]
  140. if !ok {
  141. return
  142. }
  143. if entry, ok := ccc.subConnCache[addr]; ok {
  144. if entry.sc != sc {
  145. // This could happen if NewSubConn was called multiple times for
  146. // the same address, and those SubConns are all shut down. We
  147. // remove sc immediately here.
  148. delete(ccc.subConnToAddr, sc)
  149. sc.SubConn.Shutdown()
  150. }
  151. return
  152. }
  153. entry := &subConnCacheEntry{
  154. sc: sc,
  155. }
  156. ccc.subConnCache[addr] = entry
  157. timer := time.AfterFunc(ccc.timeout, func() {
  158. ccc.mu.Lock()
  159. defer ccc.mu.Unlock()
  160. if entry.abortDeleting {
  161. return
  162. }
  163. sc.SubConn.Shutdown()
  164. delete(ccc.subConnToAddr, sc)
  165. delete(ccc.subConnCache, addr)
  166. })
  167. entry.cancel = func() {
  168. if !timer.Stop() {
  169. // If stop was not successful, the timer has fired (this can only
  170. // happen in a race). But the deleting function is blocked on ccc.mu
  171. // because the mutex was held by the caller of this function.
  172. //
  173. // Set abortDeleting to true to abort the deleting function. When
  174. // the lock is released, the deleting function will acquire the
  175. // lock, check the value of abortDeleting and return.
  176. entry.abortDeleting = true
  177. }
  178. }
  179. }
  180. func (ccc *lbCacheClientConn) UpdateState(s balancer.State) {
  181. s.Picker = &lbCachePicker{Picker: s.Picker}
  182. ccc.ClientConn.UpdateState(s)
  183. }
  184. func (ccc *lbCacheClientConn) close() {
  185. ccc.mu.Lock()
  186. defer ccc.mu.Unlock()
  187. // Only cancel all existing timers. There's no need to shut down SubConns.
  188. for _, entry := range ccc.subConnCache {
  189. entry.cancel()
  190. }
  191. }
  192. type lbCachePicker struct {
  193. balancer.Picker
  194. }
  195. func (cp *lbCachePicker) Pick(i balancer.PickInfo) (balancer.PickResult, error) {
  196. res, err := cp.Picker.Pick(i)
  197. if err != nil {
  198. return res, err
  199. }
  200. res.SubConn = res.SubConn.(*lbCacheSubConn).SubConn
  201. return res, nil
  202. }