grpclb_util.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. // NewAddress calls cc.NewAddress.
  77. func (r *lbManualResolver) NewAddress(addrs []resolver.Address) {
  78. r.ccr.NewAddress(addrs)
  79. }
  80. // NewServiceConfig calls cc.NewServiceConfig.
  81. func (r *lbManualResolver) NewServiceConfig(sc string) {
  82. r.ccr.NewServiceConfig(sc)
  83. }
  84. const subConnCacheTime = time.Second * 10
  85. // lbCacheClientConn is a wrapper balancer.ClientConn with a SubConn cache.
  86. // SubConns will be kept in cache for subConnCacheTime before being removed.
  87. //
  88. // Its new and remove methods are updated to do cache first.
  89. type lbCacheClientConn struct {
  90. cc balancer.ClientConn
  91. timeout time.Duration
  92. mu sync.Mutex
  93. // subConnCache only keeps subConns that are being deleted.
  94. subConnCache map[resolver.Address]*subConnCacheEntry
  95. subConnToAddr map[balancer.SubConn]resolver.Address
  96. }
  97. type subConnCacheEntry struct {
  98. sc balancer.SubConn
  99. cancel func()
  100. abortDeleting bool
  101. }
  102. func newLBCacheClientConn(cc balancer.ClientConn) *lbCacheClientConn {
  103. return &lbCacheClientConn{
  104. cc: cc,
  105. timeout: subConnCacheTime,
  106. subConnCache: make(map[resolver.Address]*subConnCacheEntry),
  107. subConnToAddr: make(map[balancer.SubConn]resolver.Address),
  108. }
  109. }
  110. func (ccc *lbCacheClientConn) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) {
  111. if len(addrs) != 1 {
  112. return nil, fmt.Errorf("grpclb calling NewSubConn with addrs of length %v", len(addrs))
  113. }
  114. addrWithoutMD := addrs[0]
  115. addrWithoutMD.Metadata = nil
  116. ccc.mu.Lock()
  117. defer ccc.mu.Unlock()
  118. if entry, ok := ccc.subConnCache[addrWithoutMD]; ok {
  119. // If entry is in subConnCache, the SubConn was being deleted.
  120. // cancel function will never be nil.
  121. entry.cancel()
  122. delete(ccc.subConnCache, addrWithoutMD)
  123. return entry.sc, nil
  124. }
  125. scNew, err := ccc.cc.NewSubConn(addrs, opts)
  126. if err != nil {
  127. return nil, err
  128. }
  129. ccc.subConnToAddr[scNew] = addrWithoutMD
  130. return scNew, nil
  131. }
  132. func (ccc *lbCacheClientConn) RemoveSubConn(sc balancer.SubConn) {
  133. ccc.mu.Lock()
  134. defer ccc.mu.Unlock()
  135. addr, ok := ccc.subConnToAddr[sc]
  136. if !ok {
  137. return
  138. }
  139. if entry, ok := ccc.subConnCache[addr]; ok {
  140. if entry.sc != sc {
  141. // This could happen if NewSubConn was called multiple times for the
  142. // same address, and those SubConns are all removed. We remove sc
  143. // immediately here.
  144. delete(ccc.subConnToAddr, sc)
  145. ccc.cc.RemoveSubConn(sc)
  146. }
  147. return
  148. }
  149. entry := &subConnCacheEntry{
  150. sc: sc,
  151. }
  152. ccc.subConnCache[addr] = entry
  153. timer := time.AfterFunc(ccc.timeout, func() {
  154. ccc.mu.Lock()
  155. if entry.abortDeleting {
  156. return
  157. }
  158. ccc.cc.RemoveSubConn(sc)
  159. delete(ccc.subConnToAddr, sc)
  160. delete(ccc.subConnCache, addr)
  161. ccc.mu.Unlock()
  162. })
  163. entry.cancel = func() {
  164. if !timer.Stop() {
  165. // If stop was not successful, the timer has fired (this can only
  166. // happen in a race). But the deleting function is blocked on ccc.mu
  167. // because the mutex was held by the caller of this function.
  168. //
  169. // Set abortDeleting to true to abort the deleting function. When
  170. // the lock is released, the deleting function will acquire the
  171. // lock, check the value of abortDeleting and return.
  172. entry.abortDeleting = true
  173. }
  174. }
  175. }
  176. func (ccc *lbCacheClientConn) UpdateBalancerState(s connectivity.State, p balancer.Picker) {
  177. ccc.cc.UpdateBalancerState(s, p)
  178. }
  179. func (ccc *lbCacheClientConn) close() {
  180. ccc.mu.Lock()
  181. // Only cancel all existing timers. There's no need to remove SubConns.
  182. for _, entry := range ccc.subConnCache {
  183. entry.cancel()
  184. }
  185. ccc.mu.Unlock()
  186. }