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