1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
/*
*
* Copyright 2020 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// Package hierarchy contains functions to set and get hierarchy string from
// addresses.
//
// This package is experimental.
package hierarchy
import (
"google.golang.org/grpc/resolver"
)
type pathKeyType string
const pathKey = pathKeyType("grpc.internal.address.hierarchical_path")
type pathValue []string
func (p pathValue) Equal(o interface{}) bool {
op, ok := o.(pathValue)
if !ok {
return false
}
if len(op) != len(p) {
return false
}
for i, v := range p {
if v != op[i] {
return false
}
}
return true
}
// Get returns the hierarchical path of addr.
func Get(addr resolver.Address) []string {
attrs := addr.BalancerAttributes
if attrs == nil {
return nil
}
path, _ := attrs.Value(pathKey).(pathValue)
return ([]string)(path)
}
// Set overrides the hierarchical path in addr with path.
func Set(addr resolver.Address, path []string) resolver.Address {
addr.BalancerAttributes = addr.BalancerAttributes.WithValue(pathKey, pathValue(path))
return addr
}
// Group splits a slice of addresses into groups based on
// the first hierarchy path. The first hierarchy path will be removed from the
// result.
//
// Input:
// [
//
// {addr0, path: [p0, wt0]}
// {addr1, path: [p0, wt1]}
// {addr2, path: [p1, wt2]}
// {addr3, path: [p1, wt3]}
//
// ]
//
// Addresses will be split into p0/p1, and the p0/p1 will be removed from the
// path.
//
// Output:
//
// {
// p0: [
// {addr0, path: [wt0]},
// {addr1, path: [wt1]},
// ],
// p1: [
// {addr2, path: [wt2]},
// {addr3, path: [wt3]},
// ],
// }
//
// If hierarchical path is not set, or has no path in it, the address is
// dropped.
func Group(addrs []resolver.Address) map[string][]resolver.Address {
ret := make(map[string][]resolver.Address)
for _, addr := range addrs {
oldPath := Get(addr)
if len(oldPath) == 0 {
continue
}
curPath := oldPath[0]
newPath := oldPath[1:]
newAddr := Set(addr, newPath)
ret[curPath] = append(ret[curPath], newAddr)
}
return ret
}
|