forked from cloudprober/cloudprober
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatictargets.go
83 lines (72 loc) · 2.45 KB
/
statictargets.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
// Copyright 2021 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 targets
import (
"fmt"
"net"
"strconv"
"strings"
"github.com/cloudprober/cloudprober/targets/endpoint"
)
func staticTargets(hosts string) (Targets, error) {
t, _ := baseTargets(nil, nil, nil)
sl := &staticLister{}
hostsSlice := strings.Split(hosts, ",")
if len(hostsSlice) == 1 {
hostsSlice = strings.Fields(hosts)
}
for _, host := range hostsSlice {
host = strings.TrimSpace(host)
// Make sure there is no "/" in the host name. That typically happens
// when users accidentally add URLs in hostnames.
if strings.IndexByte(host, '/') >= 0 {
return nil, fmt.Errorf("invalid host (%s), contains '/'", host)
}
hostColonParts := strings.Split(host, ":")
// There is no colon in host name.
if len(hostColonParts) == 1 {
sl.list = append(sl.list, endpoint.Endpoint{Name: host})
continue
}
// There is only 1 colon, assume it is for the port. An IPv6 address will
// more than 1 colon.
if len(hostColonParts) == 2 {
portNum, err := strconv.Atoi(hostColonParts[1])
if err != nil {
return nil, fmt.Errorf("error parsing port(%s): %v", hostColonParts[1], err)
}
sl.list = append(sl.list, endpoint.Endpoint{Name: hostColonParts[0], Port: portNum})
continue
}
// More than 1 colon. It should include an IPv6 address.
// 1. Parses as an IP address. If that fails,
// 2. Parse for IPv6 and port.
if ip := net.ParseIP(host); ip != nil {
sl.list = append(sl.list, endpoint.Endpoint{Name: host})
continue
}
hostname, port, err := net.SplitHostPort(host)
if err != nil {
return nil, fmt.Errorf("error parsing host(%s) as hostport: %v", host, err)
}
portNum, err := strconv.Atoi(port)
if err != nil {
return nil, fmt.Errorf("error parsing port(%s): %v", port, err)
}
sl.list = append(sl.list, endpoint.Endpoint{Name: hostname, Port: portNum})
}
t.lister = sl
t.resolver = globalResolver
return t, nil
}