summaryrefslogtreecommitdiff
path: root/main.go
blob: 2e9c79914ebcb6d8d23578b6ec14e1afa89a75c0 (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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package main

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

// Given a host/node name and a port number, format a string suitable
// for net.Dial.
func fmtAddress(node, port string) string {
	if isIPv6(node) {
		return fmt.Sprintf("[%s]:%s", node, port)
	}
	return fmt.Sprintf("%s:%s", node, port)
}

func isIPv6(node string) bool {
	ip := net.ParseIP(node)
	return ip != nil && ip.To4() == nil
}

var jwg JobWaitGroup

func emit(pt Point) {
	if pt == nil {
		return
	}
	fmt.Println(pt)
}

func doHostfile(fname string) {
	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
	}

	addresses := make(map[string]struct{})
	for _, address := range GetAddresses(cfg) {
		addresses[fmtAddress(address.Node, address.Port)] = struct{}{}
	}
	for address := range addresses {
		jwg.Do(hostname+"/"+address+"/tcp4", func() { emit(doAddress(hostname, "tcp4", address)) })
		jwg.Do(hostname+"/"+address+"/tcp6", func() { emit(doAddress(hostname, "tcp6", address)) })
	}
}

func doAddress(host, network, address string) Point {
	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()})
	}

	var _wg sync.WaitGroup
	_wg.Add(2)
	var resultName string
	var resultVersion string
	var resultError error
	go func() {
		defer _wg.Done()
		resultName, resultVersion, resultError = hello(addr)
	}()
	var resultPing float64
	go func() {
		defer _wg.Done()
		resultPing = Ping(addr.IP)
	}()
	_wg.Wait()

	result := map[string]interface{}{}
	if resultError == nil {
		result["name"] = resultName
		result["version"] = resultVersion
	} else {
		result["error"] = resultError
	}
	if resultPing >= 0 {
		result["ping"] = resultPing
	}

	return NewPoint("public", tags, result)
}

var dialer = net.Dialer{
	Timeout: 10 * time.Second,
}

// hello opens a TCP connection and waits for a Tinc server to say
// hello.
func hello(addr *net.TCPAddr) (name, version string, err error) {
	conn, err := dialer.Dial(addr.Network(), addr.String())
	if err != nil {
		return "", "", err
	}
	defer conn.Close()
	conn.SetDeadline(time.Now().Add(10 * time.Second))
	conn.(*net.TCPConn).CloseWrite()
	all, _ := ioutil.ReadAll(conn)
	line := strings.TrimRight(string(all), "\n")
	parts := strings.Split(line, " ")
	if len(parts) != 3 {
		return "", "", fmt.Errorf("malformed ID line: %q", line)
	}
	return parts[1], parts[2], nil
}

func main() {
	for _, fname := range os.Args[1:] {
		doHostfile(fname)
	}
	watch(time.Second)
}

func watch(d time.Duration) {
	ticker := time.NewTicker(d)
	done := make(chan map[string]time.Duration)
	go func() {
		jobs := jwg.Wait()
		ticker.Stop()
		done <- jobs
	}()
	for {
		select {
		case <-ticker.C:
			n, jobs := jwg.Status()
			if len(jobs) == 0 {
				panic("no active jobs, but wg still waiting")
			}
			line := fmt.Sprintf("%d/%d : %v", len(jobs), n, strings.Join(jobs, ", "))
			if len(line) > 70 {
				line = line[:67] + "..."
			}
			fmt.Fprintf(os.Stderr, "%-70s\r", line)
		case jobs := <-done:
			fmt.Fprintf(os.Stderr, "%-70s\n", "done")
			s := newSortHelper(jobs)
			sort.Sort(s)
			for _, job := range s.StringSlice {
				fmt.Fprintln(os.Stderr, s.times[job], job)
			}
			return
		}
	}
}

type sortHelper struct {
	times map[string]time.Duration
	sort.StringSlice
}

func (s sortHelper) Less(i, j int) bool {
	return s.times[s.StringSlice[i]] < s.times[s.StringSlice[j]]
}

func newSortHelper(jobs map[string]time.Duration) sortHelper {
	slice := make([]string, 0, len(jobs))
	for job := range jobs {
		slice = append(slice, job)
	}
	return sortHelper{times: jobs, StringSlice: slice}
}