github.com/google/cloudprober@v0.11.3/targets/statictargets.go (about) 1 // Copyright 2021 The Cloudprober 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 15 package targets 16 17 import ( 18 "fmt" 19 "net" 20 "strconv" 21 "strings" 22 23 "github.com/google/cloudprober/targets/endpoint" 24 ) 25 26 func staticTargets(hosts string) (Targets, error) { 27 t, _ := baseTargets(nil, nil, nil) 28 sl := &staticLister{} 29 30 for _, host := range strings.Split(hosts, ",") { 31 host = strings.TrimSpace(host) 32 33 // Make sure there is no "/" in the host name. That typically happens 34 // when users accidentally add URLs in hostnames. 35 if strings.IndexByte(host, '/') >= 0 { 36 return nil, fmt.Errorf("invalid host (%s), contains '/'", host) 37 } 38 39 hostColonParts := strings.Split(host, ":") 40 41 // There is no colon in host name. 42 if len(hostColonParts) == 1 { 43 sl.list = append(sl.list, endpoint.Endpoint{Name: host}) 44 continue 45 } 46 47 // There is only 1 colon, assume it is for the port. An IPv6 address will 48 // more than 1 colon. 49 if len(hostColonParts) == 2 { 50 portNum, err := strconv.Atoi(hostColonParts[1]) 51 if err != nil { 52 return nil, fmt.Errorf("error parsing port(%s): %v", hostColonParts[1], err) 53 } 54 sl.list = append(sl.list, endpoint.Endpoint{Name: hostColonParts[0], Port: portNum}) 55 continue 56 } 57 58 // More than 1 colon. It should include an IPv6 address. 59 // 1. Parses as an IP address. If that fails, 60 // 2. Parse for IPv6 and port. 61 if ip := net.ParseIP(host); ip != nil { 62 sl.list = append(sl.list, endpoint.Endpoint{Name: host}) 63 continue 64 } 65 hostname, port, err := net.SplitHostPort(host) 66 if err != nil { 67 return nil, fmt.Errorf("error parsing host(%s) as hostport: %v", host, err) 68 } 69 portNum, err := strconv.Atoi(port) 70 if err != nil { 71 return nil, fmt.Errorf("error parsing port(%s): %v", port, err) 72 } 73 sl.list = append(sl.list, endpoint.Endpoint{Name: hostname, Port: portNum}) 74 } 75 76 t.lister = sl 77 t.resolver = globalResolver 78 return t, nil 79 }