roundrobin.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 roundrobin defines a roundrobin balancer. Roundrobin balancer is
  19. // installed as one of the default balancers in gRPC, users don't need to
  20. // explicitly install this balancer.
  21. package roundrobin
  22. import (
  23. "sync"
  24. "google.golang.org/grpc/balancer"
  25. "google.golang.org/grpc/balancer/base"
  26. "google.golang.org/grpc/grpclog"
  27. "google.golang.org/grpc/internal/grpcrand"
  28. )
  29. // Name is the name of round_robin balancer.
  30. const Name = "round_robin"
  31. // newBuilder creates a new roundrobin balancer builder.
  32. func newBuilder() balancer.Builder {
  33. return base.NewBalancerBuilderV2(Name, &rrPickerBuilder{}, base.Config{HealthCheck: true})
  34. }
  35. func init() {
  36. balancer.Register(newBuilder())
  37. }
  38. type rrPickerBuilder struct{}
  39. func (*rrPickerBuilder) Build(info base.PickerBuildInfo) balancer.V2Picker {
  40. grpclog.Infof("roundrobinPicker: newPicker called with info: %v", info)
  41. if len(info.ReadySCs) == 0 {
  42. return base.NewErrPickerV2(balancer.ErrNoSubConnAvailable)
  43. }
  44. var scs []balancer.SubConn
  45. for sc := range info.ReadySCs {
  46. scs = append(scs, sc)
  47. }
  48. return &rrPicker{
  49. subConns: scs,
  50. // Start at a random index, as the same RR balancer rebuilds a new
  51. // picker when SubConn states change, and we don't want to apply excess
  52. // load to the first server in the list.
  53. next: grpcrand.Intn(len(scs)),
  54. }
  55. }
  56. type rrPicker struct {
  57. // subConns is the snapshot of the roundrobin balancer when this picker was
  58. // created. The slice is immutable. Each Get() will do a round robin
  59. // selection from it and return the selected SubConn.
  60. subConns []balancer.SubConn
  61. mu sync.Mutex
  62. next int
  63. }
  64. func (p *rrPicker) Pick(balancer.PickInfo) (balancer.PickResult, error) {
  65. p.mu.Lock()
  66. sc := p.subConns[p.next]
  67. p.next = (p.next + 1) % len(p.subConns)
  68. p.mu.Unlock()
  69. return balancer.PickResult{SubConn: sc}, nil
  70. }