weightedroundrobin.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. *
  3. * Copyright 2019 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 weightedroundrobin provides an implementation of the weighted round
  19. // robin LB policy, as defined in [gRFC A58].
  20. //
  21. // # Experimental
  22. //
  23. // Notice: This package is EXPERIMENTAL and may be changed or removed in a
  24. // later release.
  25. //
  26. // [gRFC A58]: https://github.com/grpc/proposal/blob/master/A58-client-side-weighted-round-robin-lb-policy.md
  27. package weightedroundrobin
  28. import (
  29. "fmt"
  30. "google.golang.org/grpc/resolver"
  31. )
  32. // attributeKey is the type used as the key to store AddrInfo in the
  33. // BalancerAttributes field of resolver.Address.
  34. type attributeKey struct{}
  35. // AddrInfo will be stored in the BalancerAttributes field of Address in order
  36. // to use weighted roundrobin balancer.
  37. type AddrInfo struct {
  38. Weight uint32
  39. }
  40. // Equal allows the values to be compared by Attributes.Equal.
  41. func (a AddrInfo) Equal(o interface{}) bool {
  42. oa, ok := o.(AddrInfo)
  43. return ok && oa.Weight == a.Weight
  44. }
  45. // SetAddrInfo returns a copy of addr in which the BalancerAttributes field is
  46. // updated with addrInfo.
  47. func SetAddrInfo(addr resolver.Address, addrInfo AddrInfo) resolver.Address {
  48. addr.BalancerAttributes = addr.BalancerAttributes.WithValue(attributeKey{}, addrInfo)
  49. return addr
  50. }
  51. // GetAddrInfo returns the AddrInfo stored in the BalancerAttributes field of
  52. // addr.
  53. func GetAddrInfo(addr resolver.Address) AddrInfo {
  54. v := addr.BalancerAttributes.Value(attributeKey{})
  55. ai, _ := v.(AddrInfo)
  56. return ai
  57. }
  58. func (a AddrInfo) String() string {
  59. return fmt.Sprintf("Weight: %d", a.Weight)
  60. }