grpclb_picker.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. /*
  2. *
  3. * Copyright 2017 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. "sync"
  21. "sync/atomic"
  22. "google.golang.org/grpc/balancer"
  23. lbpb "google.golang.org/grpc/balancer/grpclb/grpc_lb_v1"
  24. "google.golang.org/grpc/codes"
  25. "google.golang.org/grpc/internal/grpcrand"
  26. "google.golang.org/grpc/status"
  27. )
  28. // rpcStats is same as lbpb.ClientStats, except that numCallsDropped is a map
  29. // instead of a slice.
  30. type rpcStats struct {
  31. // Only access the following fields atomically.
  32. numCallsStarted int64
  33. numCallsFinished int64
  34. numCallsFinishedWithClientFailedToSend int64
  35. numCallsFinishedKnownReceived int64
  36. mu sync.Mutex
  37. // map load_balance_token -> num_calls_dropped
  38. numCallsDropped map[string]int64
  39. }
  40. func newRPCStats() *rpcStats {
  41. return &rpcStats{
  42. numCallsDropped: make(map[string]int64),
  43. }
  44. }
  45. func isZeroStats(stats *lbpb.ClientStats) bool {
  46. return len(stats.CallsFinishedWithDrop) == 0 &&
  47. stats.NumCallsStarted == 0 &&
  48. stats.NumCallsFinished == 0 &&
  49. stats.NumCallsFinishedWithClientFailedToSend == 0 &&
  50. stats.NumCallsFinishedKnownReceived == 0
  51. }
  52. // toClientStats converts rpcStats to lbpb.ClientStats, and clears rpcStats.
  53. func (s *rpcStats) toClientStats() *lbpb.ClientStats {
  54. stats := &lbpb.ClientStats{
  55. NumCallsStarted: atomic.SwapInt64(&s.numCallsStarted, 0),
  56. NumCallsFinished: atomic.SwapInt64(&s.numCallsFinished, 0),
  57. NumCallsFinishedWithClientFailedToSend: atomic.SwapInt64(&s.numCallsFinishedWithClientFailedToSend, 0),
  58. NumCallsFinishedKnownReceived: atomic.SwapInt64(&s.numCallsFinishedKnownReceived, 0),
  59. }
  60. s.mu.Lock()
  61. dropped := s.numCallsDropped
  62. s.numCallsDropped = make(map[string]int64)
  63. s.mu.Unlock()
  64. for token, count := range dropped {
  65. stats.CallsFinishedWithDrop = append(stats.CallsFinishedWithDrop, &lbpb.ClientStatsPerToken{
  66. LoadBalanceToken: token,
  67. NumCalls: count,
  68. })
  69. }
  70. return stats
  71. }
  72. func (s *rpcStats) drop(token string) {
  73. atomic.AddInt64(&s.numCallsStarted, 1)
  74. s.mu.Lock()
  75. s.numCallsDropped[token]++
  76. s.mu.Unlock()
  77. atomic.AddInt64(&s.numCallsFinished, 1)
  78. }
  79. func (s *rpcStats) failedToSend() {
  80. atomic.AddInt64(&s.numCallsStarted, 1)
  81. atomic.AddInt64(&s.numCallsFinishedWithClientFailedToSend, 1)
  82. atomic.AddInt64(&s.numCallsFinished, 1)
  83. }
  84. func (s *rpcStats) knownReceived() {
  85. atomic.AddInt64(&s.numCallsStarted, 1)
  86. atomic.AddInt64(&s.numCallsFinishedKnownReceived, 1)
  87. atomic.AddInt64(&s.numCallsFinished, 1)
  88. }
  89. // rrPicker does roundrobin on subConns. It's typically used when there's no
  90. // response from remote balancer, and grpclb falls back to the resolved
  91. // backends.
  92. //
  93. // It guaranteed that len(subConns) > 0.
  94. type rrPicker struct {
  95. mu sync.Mutex
  96. subConns []balancer.SubConn // The subConns that were READY when taking the snapshot.
  97. subConnsNext int
  98. }
  99. func newRRPicker(readySCs []balancer.SubConn) *rrPicker {
  100. return &rrPicker{
  101. subConns: readySCs,
  102. subConnsNext: grpcrand.Intn(len(readySCs)),
  103. }
  104. }
  105. func (p *rrPicker) Pick(balancer.PickInfo) (balancer.PickResult, error) {
  106. p.mu.Lock()
  107. defer p.mu.Unlock()
  108. sc := p.subConns[p.subConnsNext]
  109. p.subConnsNext = (p.subConnsNext + 1) % len(p.subConns)
  110. return balancer.PickResult{SubConn: sc}, nil
  111. }
  112. // lbPicker does two layers of picks:
  113. //
  114. // First layer: roundrobin on all servers in serverList, including drops and backends.
  115. // - If it picks a drop, the RPC will fail as being dropped.
  116. // - If it picks a backend, do a second layer pick to pick the real backend.
  117. //
  118. // Second layer: roundrobin on all READY backends.
  119. //
  120. // It's guaranteed that len(serverList) > 0.
  121. type lbPicker struct {
  122. mu sync.Mutex
  123. serverList []*lbpb.Server
  124. serverListNext int
  125. subConns []balancer.SubConn // The subConns that were READY when taking the snapshot.
  126. subConnsNext int
  127. stats *rpcStats
  128. }
  129. func newLBPicker(serverList []*lbpb.Server, readySCs []balancer.SubConn, stats *rpcStats) *lbPicker {
  130. return &lbPicker{
  131. serverList: serverList,
  132. subConns: readySCs,
  133. subConnsNext: grpcrand.Intn(len(readySCs)),
  134. stats: stats,
  135. }
  136. }
  137. func (p *lbPicker) Pick(balancer.PickInfo) (balancer.PickResult, error) {
  138. p.mu.Lock()
  139. defer p.mu.Unlock()
  140. // Layer one roundrobin on serverList.
  141. s := p.serverList[p.serverListNext]
  142. p.serverListNext = (p.serverListNext + 1) % len(p.serverList)
  143. // If it's a drop, return an error and fail the RPC.
  144. if s.Drop {
  145. p.stats.drop(s.LoadBalanceToken)
  146. return balancer.PickResult{}, status.Errorf(codes.Unavailable, "request dropped by grpclb")
  147. }
  148. // If not a drop but there's no ready subConns.
  149. if len(p.subConns) <= 0 {
  150. return balancer.PickResult{}, balancer.ErrNoSubConnAvailable
  151. }
  152. // Return the next ready subConn in the list, also collect rpc stats.
  153. sc := p.subConns[p.subConnsNext]
  154. p.subConnsNext = (p.subConnsNext + 1) % len(p.subConns)
  155. done := func(info balancer.DoneInfo) {
  156. if !info.BytesSent {
  157. p.stats.failedToSend()
  158. } else if info.BytesReceived {
  159. p.stats.knownReceived()
  160. }
  161. }
  162. return balancer.PickResult{SubConn: sc, Done: done}, nil
  163. }
  164. func (p *lbPicker) updateReadySCs(readySCs []balancer.SubConn) {
  165. p.mu.Lock()
  166. defer p.mu.Unlock()
  167. p.subConns = readySCs
  168. p.subConnsNext = p.subConnsNext % len(readySCs)
  169. }