-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathinfping.go
255 lines (219 loc) · 5.27 KB
/
infping.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
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package main
import (
"bufio"
"encoding/json"
"fmt"
"github.com/influxdata/influxdb/client/v2"
"github.com/pelletier/go-toml"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"reflect"
"strconv"
"strings"
"time"
)
const (
path = "config.toml"
)
var (
newnodes = make(map[string]string)
oldnodes = make(map[string]string)
change bool = false
)
type Consul []struct {
ID string `json:"ID"`
Node string `json:"Node"`
Address string `json:"Address"`
Datacenter string `json:"Datacenter"`
TaggedAddresses struct {
Lan string `json:"lan"`
Wan string `json:"wan"`
} `json:"TaggedAddresses"`
Meta struct {
} `json:"Meta"`
CreateIndex int `json:"CreateIndex"`
ModifyIndex int `json:"ModifyIndex"`
}
func watchNodes(url string) {
var first bool = true
for {
newnodes = getNodes(url)
// Check if any change of consul nodes
if reflect.DeepEqual(newnodes, oldnodes) {
// give time for requests newnodes
time.Sleep(5 * time.Second)
} else {
if first {
first = false
} else {
change = true
}
oldnodes = newnodes
}
}
}
func getNodes(url string) (nodes map[string]string) {
nodes = make(map[string]string)
data := getJson(url)
cfg := Consul{}
err := json.Unmarshal([]byte(data), &cfg)
perr(err)
for v := range cfg {
nodes[cfg[v].Address] = cfg[v].Node
}
return
}
func getJson(url string) (json string) {
resp, err := http.Get(url)
herr(err)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
perr(err)
if resp.StatusCode == 200 {
json = string(body)
} else {
log.Println(resp.Status)
json = "[]"
}
return json
}
func herr(err error) {
if err != nil {
log.Println(err)
os.Exit(1)
}
}
func perr(err error) {
if err != nil {
log.Println(err)
}
}
func slashSplitter(c rune) bool {
return c == '/'
}
func readPoints(config *toml.Tree, con client.Client) {
START:
nodes := newnodes
args := []string{"-B 1", "-D", "-r0", "-O 0", "-Q 10", "-p 1000", "-l"}
list := []string{}
for u := range nodes {
ip := u
args = append(args, ip)
list = append(list, ip)
}
log.Printf("Going to ping the following ips: %v", list)
cmd := exec.Command("/usr/bin/fping", args...)
stdout, err := cmd.StdoutPipe()
herr(err)
stderr, err := cmd.StderrPipe()
herr(err)
cmd.Start()
perr(err)
buff := bufio.NewScanner(stderr)
for buff.Scan() {
text := buff.Text()
fields := strings.Fields(text)
// Ignore timestamp
if len(fields) > 1 {
ip := fields[0]
data := fields[4]
dataSplitted := strings.FieldsFunc(data, slashSplitter)
// Remove ,
dataSplitted[2] = strings.TrimRight(dataSplitted[2], "%,")
sent, recv, lossp := dataSplitted[0], dataSplitted[1], dataSplitted[2]
min, max, avg := "", "", ""
// Ping times
if len(fields) > 5 {
times := fields[7]
td := strings.FieldsFunc(times, slashSplitter)
min, avg, max = td[0], td[1], td[2]
}
log.Printf("Node:%s, IP:%s, send:%s, recv:%s loss: %s, min: %s, avg: %s, max: %s", nodes[ip], ip, sent, recv, lossp, min, avg, max)
writePoints(config, con, nodes, ip, sent, recv, lossp, min, avg, max)
}
// Restart scan if nodes change
if change {
log.Println("Nodes updated : Restarting fping")
change = false
cmd.Process.Kill()
cmd.Wait()
goto START
}
}
std := bufio.NewReader(stdout)
line, err := std.ReadString('\n')
perr(err)
log.Printf("stdout:%s", line)
}
func writePoints(config *toml.Tree, con client.Client, nodes map[string]string, ip string, sent string, recv string, lossp string, min string, avg string, max string) {
db := config.Get("influxdb.db").(string)
ms := config.Get("influxdb.measurement").(string)
ps := config.Get("influxdb.precision").(string)
rp := config.Get("influxdb.retentionpolicy").(string)
loss, _ := strconv.Atoi(lossp)
fields := map[string]interface{}{}
if min != "" && avg != "" && max != "" {
min, _ := strconv.ParseFloat(min, 64)
avg, _ := strconv.ParseFloat(avg, 64)
max, _ := strconv.ParseFloat(max, 64)
fields = map[string]interface{}{
"loss": loss,
"min": min,
"avg": avg,
"max": max,
}
} else {
fields = map[string]interface{}{
"loss": loss,
}
}
// Create a new point batch
bp, err := client.NewBatchPoints(client.BatchPointsConfig{
Database: db,
Precision: ps,
RetentionPolicy: rp,
})
if err != nil {
log.Fatal(err)
}
// Create a point and add to batch
tags := map[string]string{
"node": nodes[ip],
"addr": ip,
}
pt, err := client.NewPoint(ms, tags, fields, time.Now())
if err != nil {
log.Fatal(err)
}
bp.AddPoint(pt)
// Write the batch
if err := con.Write(bp); err != nil {
log.Fatal(err)
}
}
func main() {
config, err := toml.LoadFile(path)
herr(err)
host := config.Get("influxdb.host").(string)
port := config.Get("influxdb.port").(string)
username := config.Get("influxdb.user").(string)
password := config.Get("influxdb.pass").(string)
addr := fmt.Sprintf("http://%s:%s", host, port)
// Create a new HTTPClient
con, err := client.NewHTTPClient(client.HTTPConfig{
Addr: addr,
Username: username,
Password: password,
})
herr(err)
dur, ver, err := con.Ping(1)
herr(err)
log.Printf("Connected to influxdb! (dur:%v, ver:%s)", dur, ver)
url := config.Get("consul.url").(string)
newnodes = getNodes(url)
go watchNodes(url)
readPoints(config, con)
}