balancer.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2016 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 clientv3
  15. import (
  16. "net/url"
  17. "strings"
  18. "sync/atomic"
  19. "golang.org/x/net/context"
  20. "google.golang.org/grpc"
  21. )
  22. // simpleBalancer does the bare minimum to expose multiple eps
  23. // to the grpc reconnection code path
  24. type simpleBalancer struct {
  25. // eps are the client's endpoints stripped of any URL scheme
  26. eps []string
  27. ch chan []grpc.Address
  28. numGets uint32
  29. }
  30. func newSimpleBalancer(eps []string) grpc.Balancer {
  31. ch := make(chan []grpc.Address, 1)
  32. addrs := make([]grpc.Address, len(eps))
  33. for i := range eps {
  34. addrs[i].Addr = getHost(eps[i])
  35. }
  36. ch <- addrs
  37. return &simpleBalancer{eps: eps, ch: ch}
  38. }
  39. func (b *simpleBalancer) Start(target string) error { return nil }
  40. func (b *simpleBalancer) Up(addr grpc.Address) func(error) { return func(error) {} }
  41. func (b *simpleBalancer) Get(ctx context.Context, opts grpc.BalancerGetOptions) (grpc.Address, func(), error) {
  42. v := atomic.AddUint32(&b.numGets, 1)
  43. ep := b.eps[v%uint32(len(b.eps))]
  44. return grpc.Address{Addr: getHost(ep)}, func() {}, nil
  45. }
  46. func (b *simpleBalancer) Notify() <-chan []grpc.Address { return b.ch }
  47. func (b *simpleBalancer) Close() error {
  48. close(b.ch)
  49. return nil
  50. }
  51. func getHost(ep string) string {
  52. url, uerr := url.Parse(ep)
  53. if uerr != nil || !strings.Contains(ep, "://") {
  54. return ep
  55. }
  56. return url.Host
  57. }