You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

196 lines
5.7 KiB

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