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
|
package main
import (
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
"strings"
"sync"
)
func fmtAddress(node, port string) string {
if isIPv6(node) {
return fmt.Sprintf("[%s]:%s", node, port)
} else {
return fmt.Sprintf("%s:%s", node, port)
}
}
func isIPv6(node string) bool {
ip := net.ParseIP(node)
return ip != nil && ip.To4() == nil
}
var wg sync.WaitGroup
func Emit(pt Point) {
if pt == nil {
return
}
fmt.Println(pt)
}
func DoHostfile(fname string) {
defer wg.Done()
hostname := filepath.Base(fname)
cfg, err := readConfigFile(fname)
if err != nil {
Emit(NewPoint("public", map[string]string{"host": hostname}, map[string]interface{}{"error": err.Error()}))
return
}
for _, address := range getAddresses(cfg) {
addressStr := fmtAddress(address.Node, address.Port)
wg.Add(2)
go Emit(DoAddress(hostname, "tcp4", addressStr))
go Emit(DoAddress(hostname, "tcp6", addressStr))
}
}
func DoAddress(host, network, address string) Point {
defer wg.Done()
tags := map[string]string{
"host": host,
"network": network,
"address": address,
}
addr, err := net.ResolveTCPAddr(network, address)
if err != nil {
if ae, ok := err.(*net.AddrError); ok && ae.Err == "no suitable address found" {
return nil
}
return NewPoint("public", tags, map[string]interface{}{"error": err.Error()})
}
conn, err := net.DialTCP(network, nil, addr)
if err != nil {
return NewPoint("public", tags, map[string]interface{}{"error": err.Error()})
}
conn.CloseWrite()
all, _ := ioutil.ReadAll(conn)
line := strings.TrimRight(string(all), "\n")
parts := strings.Split(line, " ")
if len(parts) != 3 {
return NewPoint("public", tags, map[string]interface{}{"error": fmt.Sprintf("malformed ID line: %q", line)})
}
return NewPoint("public", tags, map[string]interface{}{
"name": parts[1],
"version": parts[2],
})
}
func main() {
for _, fname := range os.Args[1:] {
wg.Add(1)
go DoHostfile(fname)
}
wg.Wait()
}
|