forked from aputs/kube-register
-
Notifications
You must be signed in to change notification settings - Fork 0
/
machines.go
80 lines (74 loc) · 1.78 KB
/
machines.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
package main
import (
"errors"
"fmt"
"log"
"net"
"net/http"
"net/url"
"github.com/coreos/fleet/client"
)
func getMachines(endpoint string, metadata map[string][]string, reverseLookup bool) ([]string, error) {
dialFunc := net.Dial
machineList := make([]string, 0)
u, err := url.Parse(endpoint)
if err != nil {
return nil, err
}
if u.Scheme == "unix" {
endpoint = "http://domain-sock/"
dialFunc = func(network, addr string) (net.Conn, error) {
return net.Dial("unix", u.Path)
}
}
c := &http.Client{
Transport: &http.Transport{
Dial: dialFunc,
DisableKeepAlives: true,
},
}
fleetClient, err := client.NewHTTPClient(c, endpoint)
if err != nil {
return nil, err
}
machines, err := fleetClient.Machines()
if err != nil {
return nil, err
}
for _, m := range machines {
if hasMetadata(m, metadata) && isHealthy(m.PublicIP) {
if reverseLookup {
hostnames, err := net.LookupAddr(m.PublicIP)
if err != nil {
return nil, err
}
if len(hostnames) < 1 {
return nil, errors.New("Could not get hostname for IP " + m.PublicIP)
}
hostname := hostnames[0]
// remove trailing dot
if hostname[len(hostname)-1] == '.' {
hostname = hostname[:len(hostname)-1]
}
machineList = append(machineList, hostname)
} else {
machineList = append(machineList, m.PublicIP)
}
}
}
return machineList, nil
}
func isHealthy(addr string) bool {
url := fmt.Sprintf("http://%s:%d/healthz", addr, 10250)
res, err := http.Get(url)
if err != nil {
log.Printf("error health checking %s: %s", addr, err)
return false
}
defer res.Body.Close()
if res.StatusCode >= http.StatusOK && res.StatusCode < http.StatusBadRequest {
return true
}
log.Printf("unhealthy machine: %s will not be registered", addr)
return false
}