picker.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright 2018 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package picker
  15. import (
  16. "fmt"
  17. "go.uber.org/zap"
  18. "google.golang.org/grpc/balancer"
  19. "google.golang.org/grpc/resolver"
  20. )
  21. // Picker defines balancer Picker methods.
  22. type Picker interface {
  23. balancer.Picker
  24. String() string
  25. }
  26. // Config defines picker configuration.
  27. type Config struct {
  28. // Policy specifies etcd clientv3's built in balancer policy.
  29. Policy Policy
  30. // Logger defines picker logging object.
  31. Logger *zap.Logger
  32. // SubConnToResolverAddress maps each gRPC sub-connection to an address.
  33. // Basically, it is a list of addresses that the Picker can pick from.
  34. SubConnToResolverAddress map[balancer.SubConn]resolver.Address
  35. }
  36. // Policy defines balancer picker policy.
  37. type Policy uint8
  38. const (
  39. // Error is error picker policy.
  40. Error Policy = iota
  41. // RoundrobinBalanced balances loads over multiple endpoints
  42. // and implements failover in roundrobin fashion.
  43. RoundrobinBalanced
  44. // Custom defines custom balancer picker.
  45. // TODO: custom picker is not supported yet.
  46. Custom
  47. )
  48. func (p Policy) String() string {
  49. switch p {
  50. case Error:
  51. return "picker-error"
  52. case RoundrobinBalanced:
  53. return "picker-roundrobin-balanced"
  54. case Custom:
  55. panic("'custom' picker policy is not supported yet")
  56. default:
  57. panic(fmt.Errorf("invalid balancer picker policy (%d)", p))
  58. }
  59. }
  60. // New creates a new Picker.
  61. func New(cfg Config) Picker {
  62. switch cfg.Policy {
  63. case Error:
  64. panic("'error' picker policy is not supported here; use 'picker.NewErr'")
  65. case RoundrobinBalanced:
  66. return newRoundrobinBalanced(cfg)
  67. case Custom:
  68. panic("'custom' picker policy is not supported yet")
  69. default:
  70. panic(fmt.Errorf("invalid balancer picker policy (%d)", cfg.Policy))
  71. }
  72. }