summaryrefslogtreecommitdiff
path: root/main.go
blob: 2c32c413aba94dac9351295460b69ca5d6b3e725 (plain)
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
package main

import (
	"fmt"
	"io/ioutil"
	"net"
	"os"
	"path/filepath"
	"strings"
	"sync"
)

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) {
		wg.Add(2)
		go Emit(DoAddress(hostname, "tcp4", address))
		go Emit(DoAddress(hostname, "tcp6", address))
	}
}

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()
}