roundrobin.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. "context"
  24. "sync"
  25. "google.golang.org/grpc/balancer"
  26. "google.golang.org/grpc/balancer/base"
  27. "google.golang.org/grpc/grpclog"
  28. "google.golang.org/grpc/resolver"
  29. )
  30. // Name is the name of round_robin balancer.
  31. const Name = "round_robin"
  32. // newBuilder creates a new roundrobin balancer builder.
  33. func newBuilder() balancer.Builder {
  34. return base.NewBalancerBuilderWithConfig(Name, &rrPickerBuilder{}, base.Config{HealthCheck: true})
  35. }
  36. func init() {
  37. balancer.Register(newBuilder())
  38. }
  39. type rrPickerBuilder struct{}
  40. func (*rrPickerBuilder) Build(readySCs map[resolver.Address]balancer.SubConn) balancer.Picker {
  41. grpclog.Infof("roundrobinPicker: newPicker called with readySCs: %v", readySCs)
  42. var scs []balancer.SubConn
  43. for _, sc := range readySCs {
  44. scs = append(scs, sc)
  45. }
  46. return &rrPicker{
  47. subConns: scs,
  48. }
  49. }
  50. type rrPicker struct {
  51. // subConns is the snapshot of the roundrobin balancer when this picker was
  52. // created. The slice is immutable. Each Get() will do a round robin
  53. // selection from it and return the selected SubConn.
  54. subConns []balancer.SubConn
  55. mu sync.Mutex
  56. next int
  57. }
  58. func (p *rrPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) {
  59. if len(p.subConns) <= 0 {
  60. return nil, nil, balancer.ErrNoSubConnAvailable
  61. }
  62. p.mu.Lock()
  63. sc := p.subConns[p.next]
  64. p.next = (p.next + 1) % len(p.subConns)
  65. p.mu.Unlock()
  66. return sc, nil, nil
  67. }