-
Notifications
You must be signed in to change notification settings - Fork 77
/
endpoint.go
193 lines (167 loc) · 4.88 KB
/
endpoint.go
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// Copyright 2019 The Cloudprober 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 endpoint provides the type Endpoint, to be used with the
// targets.Targets interface.
package endpoint
import (
"fmt"
"net"
"net/url"
"sort"
"strconv"
"strings"
"time"
"github.com/cloudprober/cloudprober/common/iputils"
targetspb "github.com/cloudprober/cloudprober/targets/proto"
)
// Endpoint represents a targets and associated parameters.
type Endpoint struct {
Name string
Labels map[string]string
LastUpdated time.Time
Port int
IP net.IP
}
// Key returns a string key that uniquely identifies that endpoint.
// Endpoint key consists of endpoint name, port and labels.
func (ep *Endpoint) Key() string {
labelSlice := make([]string, len(ep.Labels))
i := 0
for k, v := range ep.Labels {
labelSlice[i] = k + ":" + v
i++
}
sort.Strings(labelSlice)
ip := ""
if ep.IP != nil {
ip = ep.IP.String()
}
return strings.Join(append([]string{ep.Name, ip, strconv.Itoa(ep.Port)}, labelSlice...), "_")
}
// Lister should implement the ListEndpoints method.
type Lister interface {
// ListEndpoints returns list of endpoints (name, port tupples).
ListEndpoints() []Endpoint
}
type Resolver interface {
// Resolve, given a target and IP Version will return the IP address for that
// target.
Resolve(name string, ipVer int) (net.IP, error)
}
// EndpointsFromNames is convenience function to build a list of endpoints
// from only names. It leaves the Port field in Endpoint unset and initializes
// Labels field to an empty map.
func EndpointsFromNames(names []string) []Endpoint {
result := make([]Endpoint, len(names))
for i, name := range names {
result[i].Name = name
result[i].Labels = make(map[string]string)
}
return result
}
// Dst return the "dst" label for the endpoint
func (ep *Endpoint) Dst() string {
if ep.Port == 0 {
return ep.Name
}
return net.JoinHostPort(ep.Name, strconv.Itoa(ep.Port))
}
type resolverOptions struct {
nameOverride string
}
type ResolverOption func(*resolverOptions)
func WithNameOverride(nameOverride string) ResolverOption {
return func(ro *resolverOptions) {
ro.nameOverride = nameOverride
}
}
// Resolve resolves endpoint to an IP address. If endpoint has an embedded IP
// address it uses that, otherwise a global reolver is used.
func (ep *Endpoint) Resolve(ipVersion int, resolver Resolver, opts ...ResolverOption) (net.IP, error) {
ro := &resolverOptions{}
for _, opt := range opts {
opt(ro)
}
if ep.IP != nil {
if ipVersion == 0 || iputils.IPVersion(ep.IP) == ipVersion {
return ep.IP, nil
}
return nil, fmt.Errorf("no IPv%d address (IP: %s) for %s", ipVersion, ep.IP.String(), ep.Name)
}
name := ep.Name
if ro.nameOverride != "" {
name = ro.nameOverride
}
return resolver.Resolve(name, ipVersion)
}
// NamesFromEndpoints is convenience function to build a list of names
// from endpoints.
func NamesFromEndpoints(endpoints []Endpoint) []string {
result := make([]string, len(endpoints))
for i, ep := range endpoints {
result[i] = ep.Name
}
return result
}
func parseURL(s string) (scheme, host, path string, port int, err error) {
u, err := url.Parse(s)
if err != nil {
return "", "", "", 0, fmt.Errorf("invalid URL: %v", err)
}
scheme = u.Scheme
host = u.Hostname()
port, _ = strconv.Atoi(u.Port())
path = "/"
hostPath := strings.TrimPrefix(s, scheme+"://")
if i := strings.Index(hostPath, "/"); i != -1 {
path = hostPath[i:]
}
return scheme, host, path, port, nil
}
func FromProtoMessage(endpointspb []*targetspb.Endpoint) ([]Endpoint, error) {
var endpoints []Endpoint
seen := make(map[string]bool)
timestamp := time.Now()
for _, pb := range endpointspb {
ep := Endpoint{
Name: pb.GetName(),
Labels: pb.GetLabels(),
IP: net.ParseIP(pb.GetIp()),
Port: int(pb.GetPort()),
LastUpdated: timestamp,
}
if pb.GetUrl() != "" {
scheme, host, path, port, err := parseURL(pb.GetUrl())
if err != nil {
return nil, err
}
if ep.Labels == nil {
ep.Labels = make(map[string]string)
}
ep.Labels["__cp_scheme__"] = scheme
ep.Labels["__cp_host__"] = host
ep.Labels["__cp_path__"] = path
if ep.Port == 0 {
ep.Port = port
}
}
epKey := ep.Key()
if seen[epKey] {
return nil, fmt.Errorf("duplicate endpoint: %s", ep.Key())
}
seen[epKey] = true
endpoints = append(endpoints, ep)
}
return endpoints, nil
}