utils.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 balancer
  15. import (
  16. "fmt"
  17. "net/url"
  18. "sort"
  19. "sync/atomic"
  20. "time"
  21. "google.golang.org/grpc/balancer"
  22. "google.golang.org/grpc/resolver"
  23. )
  24. func scToString(sc balancer.SubConn) string {
  25. return fmt.Sprintf("%p", sc)
  26. }
  27. func scsToStrings(scs map[balancer.SubConn]resolver.Address) (ss []string) {
  28. ss = make([]string, 0, len(scs))
  29. for sc, a := range scs {
  30. ss = append(ss, fmt.Sprintf("%s (%s)", a.Addr, scToString(sc)))
  31. }
  32. sort.Strings(ss)
  33. return ss
  34. }
  35. func addrsToStrings(addrs []resolver.Address) (ss []string) {
  36. ss = make([]string, len(addrs))
  37. for i := range addrs {
  38. ss[i] = addrs[i].Addr
  39. }
  40. sort.Strings(ss)
  41. return ss
  42. }
  43. func epsToAddrs(eps ...string) (addrs []resolver.Address) {
  44. addrs = make([]resolver.Address, 0, len(eps))
  45. for _, ep := range eps {
  46. u, err := url.Parse(ep)
  47. if err != nil {
  48. addrs = append(addrs, resolver.Address{Addr: ep, Type: resolver.Backend})
  49. continue
  50. }
  51. addrs = append(addrs, resolver.Address{Addr: u.Host, Type: resolver.Backend})
  52. }
  53. return addrs
  54. }
  55. var genN = new(uint32)
  56. func genName() string {
  57. now := time.Now().UnixNano()
  58. return fmt.Sprintf("%X%X", now, atomic.AddUint32(genN, 1))
  59. }