forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
494 lines (428 loc) · 12.5 KB
/
util.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
package monitors
import (
"errors"
"fmt"
"net"
"time"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/heartbeat/look"
)
type funcJob struct {
settings JobSettings
funcTask
}
type funcTask struct {
run func() (common.MapStr, []TaskRunner, error)
}
// IPSettings provides common configuration settings for IP resolution and ping
// mode.
type IPSettings struct {
IPv4 bool `config:"ipv4"`
IPv6 bool `config:"ipv6"`
Mode PingMode `config:"mode"`
}
// JobSettings configures a Job name and global fields to be added to every
// event.
type JobSettings struct {
Name string
Fields common.MapStr
}
// HostJobSettings configures a Job including Host lookups and global fields to be added
// to every event.
type HostJobSettings struct {
Name string
Host string
IP IPSettings
Fields common.MapStr
}
// PingMode enumeration for configuring `any` or `all` IPs pinging.
type PingMode uint8
const (
PingModeUndefined PingMode = iota
PingAny
PingAll
)
// DefaultIPSettings provides an instance of default IPSettings to be copied
// when unpacking settings from a common.Config object.
var DefaultIPSettings = IPSettings{
IPv4: true,
IPv6: true,
Mode: PingAny,
}
// Network determines the Network type used for IP name resolution, based on the
// provided settings.
func (s IPSettings) Network() string {
switch {
case s.IPv4 && !s.IPv6:
return "ip4"
case !s.IPv4 && s.IPv6:
return "ip6"
case s.IPv4 && s.IPv6:
return "ip"
}
return ""
}
// MakeSimpleJob creates a new Job from a callback function. The callback should
// return an valid event and can not create any sub-tasks to be executed after
// completion.
func MakeSimpleJob(settings JobSettings, f func() (common.MapStr, error)) Job {
return MakeJob(settings, func() (common.MapStr, []TaskRunner, error) {
event, err := f()
return event, nil, err
})
}
// MakeJob create a new Job from a callback function. The callback can
// optionally return an event to be published and a set of derived sub-tasks to be
// scheduled. The sub-tasks will be run only once and removed from the scheduler
// after completion.
func MakeJob(settings JobSettings, f func() (common.MapStr, []TaskRunner, error)) Job {
settings.AddFields(common.MapStr{
"monitor": common.MapStr{
"id": settings.Name,
},
})
return &funcJob{settings, funcTask{func() (common.MapStr, []TaskRunner, error) {
return annotated(settings, time.Now(), f).Run()
}}}
}
// MakeCont wraps a function into an executable TaskRunner. The task being generated
// can optionally return an event and/or sub-tasks.
func MakeCont(f func() (common.MapStr, []TaskRunner, error)) TaskRunner {
return funcTask{f}
}
// MakeSimpleCont wraps a function into an executable TaskRunner. The task bein generated
// should return an event to be reported.
func MakeSimpleCont(f func() (common.MapStr, error)) TaskRunner {
return MakeCont(func() (common.MapStr, []TaskRunner, error) {
event, err := f()
return event, nil, err
})
}
// MakePingIPFactory creates a factory for building a Task from a new IP address.
func MakePingIPFactory(
f func(*net.IPAddr) (common.MapStr, error),
) func(*net.IPAddr) TaskRunner {
return func(ip *net.IPAddr) TaskRunner {
return MakeSimpleCont(func() (common.MapStr, error) { return f(ip) })
}
}
var emptyTask = MakeSimpleCont(func() (common.MapStr, error) { return nil, nil })
// MakePingAllIPFactory wraps a function for building a recursive Task Runner from function callbacks.
func MakePingAllIPFactory(
f func(*net.IPAddr) []func() (common.MapStr, error),
) func(*net.IPAddr) TaskRunner {
return func(ip *net.IPAddr) TaskRunner {
cont := f(ip)
switch len(cont) {
case 0:
return emptyTask
case 1:
return MakeSimpleCont(cont[0])
}
tasks := make([]TaskRunner, len(cont))
for i, c := range cont {
tasks[i] = MakeSimpleCont(c)
}
return MakeCont(func() (common.MapStr, []TaskRunner, error) {
return nil, tasks, nil
})
}
}
// MakePingAllIPPortFactory builds a set of TaskRunner supporting a set of
// IP/port-pairs.
func MakePingAllIPPortFactory(
ports []uint16,
f func(*net.IPAddr, uint16) (common.MapStr, error),
) func(*net.IPAddr) TaskRunner {
if len(ports) == 1 {
port := ports[0]
return MakePingIPFactory(func(ip *net.IPAddr) (common.MapStr, error) {
return f(ip, port)
})
}
return MakePingAllIPFactory(func(ip *net.IPAddr) []func() (common.MapStr, error) {
funcs := make([]func() (common.MapStr, error), len(ports))
for i := range ports {
port := ports[i]
funcs[i] = func() (common.MapStr, error) {
return f(ip, port)
}
}
return funcs
})
}
// MakeByIPJob builds a new Job based on already known IP. Similar to
// MakeByHostJob, the pingFactory will be used to build the tasks run by the job.
//
// A pingFactory instance is normally build with MakePingIPFactory,
// MakePingAllIPFactory or MakePingAllIPPortFactory.
func MakeByIPJob(
settings JobSettings,
ip net.IP,
pingFactory func(ip *net.IPAddr) TaskRunner,
) (Job, error) {
// use ResolveIPAddr to parse the ip into net.IPAddr adding a zone info
// if ipv6 is used.
addr, err := net.ResolveIPAddr("ip", ip.String())
if err != nil {
return nil, err
}
fields := common.MapStr{
"monitor": common.MapStr{"ip": addr.String()},
}
return MakeJob(settings, WithFields(fields, pingFactory(addr)).Run), nil
}
// MakeByHostJob creates a new Job including host lookup. The pingFactory will be used to
// build one or multiple Tasks after name lookup according to settings.
//
// A pingFactory instance is normally build with MakePingIPFactory,
// MakePingAllIPFactory or MakePingAllIPPortFactory.
func MakeByHostJob(
settings HostJobSettings,
pingFactory func(ip *net.IPAddr) TaskRunner,
) (Job, error) {
host := settings.Host
if ip := net.ParseIP(host); ip != nil {
return MakeByIPJob(settings.jobSettings(), ip, pingFactory)
}
network := settings.IP.Network()
if network == "" {
return nil, errors.New("pinging hosts requires ipv4 or ipv6 mode enabled")
}
mode := settings.IP.Mode
settings.AddFields(common.MapStr{
"monitor": common.MapStr{
"host": host,
},
})
if mode == PingAny {
return makeByHostAnyIPJob(settings, host, pingFactory), nil
}
return makeByHostAllIPJob(settings, host, pingFactory), nil
}
func makeByHostAnyIPJob(
settings HostJobSettings,
host string,
pingFactory func(ip *net.IPAddr) TaskRunner,
) Job {
network := settings.IP.Network()
return MakeJob(settings.jobSettings(), func() (common.MapStr, []TaskRunner, error) {
resolveStart := time.Now()
ip, err := net.ResolveIPAddr(network, host)
if err != nil {
return resolveErr(host, err)
}
resolveEnd := time.Now()
resolveRTT := resolveEnd.Sub(resolveStart)
event := resolveIPEvent(host, ip.String(), resolveRTT)
return WithFields(event, pingFactory(ip)).Run()
})
}
func makeByHostAllIPJob(
settings HostJobSettings,
host string,
pingFactory func(ip *net.IPAddr) TaskRunner,
) Job {
network := settings.IP.Network()
filter := makeIPFilter(network)
return MakeJob(settings.jobSettings(), func() (common.MapStr, []TaskRunner, error) {
// TODO: check for better DNS IP lookup support:
// - The net.LookupIP drops ipv6 zone index
//
resolveStart := time.Now()
ips, err := net.LookupIP(host)
if err != nil {
return resolveErr(host, err)
}
resolveEnd := time.Now()
resolveRTT := resolveEnd.Sub(resolveStart)
if filter != nil {
ips = filterIPs(ips, filter)
}
if len(ips) == 0 {
err := fmt.Errorf("no %v address resolvable for host %v", network, host)
return resolveErr(host, err)
}
// create ip ping tasks
cont := make([]TaskRunner, len(ips))
for i, ip := range ips {
addr := &net.IPAddr{IP: ip}
event := resolveIPEvent(host, ip.String(), resolveRTT)
cont[i] = WithFields(event, pingFactory(addr))
}
return nil, cont, nil
})
}
func resolveIPEvent(host, ip string, rtt time.Duration) common.MapStr {
return common.MapStr{
"monitor": common.MapStr{
"host": host,
"ip": ip,
},
"resolve": common.MapStr{
"host": host,
"ip": ip,
"rtt": look.RTT(rtt),
},
}
}
func resolveErr(host string, err error) (common.MapStr, []TaskRunner, error) {
event := common.MapStr{
"monitor": common.MapStr{
"host": host,
},
"resolve": common.MapStr{
"host": host,
},
}
return event, nil, err
}
// WithFields wraps a TaskRunner, updating all events returned with the set of
// fields configured.
func WithFields(fields common.MapStr, r TaskRunner) TaskRunner {
return MakeCont(func() (common.MapStr, []TaskRunner, error) {
event, cont, err := r.Run()
if event == nil {
event = common.MapStr{}
}
event.DeepUpdate(fields)
for i := range cont {
cont[i] = WithFields(fields, cont[i])
}
return event, cont, err
})
}
// WithDuration wraps a TaskRunner, measuring the duration between creation and
// finish of the actual task and sub-tasks.
func WithDuration(field string, r TaskRunner) TaskRunner {
return MakeCont(func() (common.MapStr, []TaskRunner, error) {
return withStart(field, time.Now(), r).Run()
})
}
func withStart(field string, start time.Time, r TaskRunner) TaskRunner {
return MakeCont(func() (common.MapStr, []TaskRunner, error) {
event, cont, err := r.Run()
if event != nil {
event.Put(field, look.RTT(time.Since(start)))
}
for i := range cont {
cont[i] = withStart(field, start, cont[i])
}
return event, cont, err
})
}
func (f *funcJob) Name() string { return f.settings.Name }
func (f funcTask) Run() (common.MapStr, []TaskRunner, error) { return f.run() }
func (f funcTask) annotated(settings JobSettings, start time.Time) TaskRunner {
return annotated(settings, start, f.run)
}
// Unpack sets PingMode from a constant string. Unpack will be called by common.Unpack when
// unpacking into an IPSettings type.
func (p *PingMode) Unpack(s string) error {
switch s {
case "all":
*p = PingAll
case "any":
*p = PingAny
default:
return fmt.Errorf("expecting 'any' or 'all', not '%v'", s)
}
return nil
}
func annotated(
settings JobSettings,
start time.Time,
fn func() (common.MapStr, []TaskRunner, error),
) TaskRunner {
return MakeCont(func() (common.MapStr, []TaskRunner, error) {
event, cont, err := fn()
if err != nil {
if event == nil {
event = common.MapStr{}
}
event["error"] = look.Reason(err)
}
if event != nil {
status := look.Status(err)
event.DeepUpdate(common.MapStr{
"@timestamp": look.Timestamp(start),
"monitor": common.MapStr{
"duration": look.RTT(time.Since(start)),
"status": status,
},
})
if fields := settings.Fields; fields != nil {
event.DeepUpdate(fields)
}
}
for i := range cont {
if fcont, ok := cont[i].(funcTask); ok {
cont[i] = fcont.annotated(settings, start)
} else {
cont[i] = annotated(settings, start, cont[i].Run)
}
}
return event, cont, nil
})
}
func makeIPFilter(network string) func(net.IP) bool {
switch network {
case "ip4":
return func(i net.IP) bool { return i.To4() != nil }
case "ip6":
return func(i net.IP) bool { return i.To4() == nil && i.To16() != nil }
}
return nil
}
func filterIPs(ips []net.IP, filt func(net.IP) bool) []net.IP {
out := ips[:0]
for _, ip := range ips {
if filt(ip) {
out = append(out, ip)
}
}
return out
}
// MakeJobSetting creates a new JobSettings structure without any global event fields.
func MakeJobSetting(name string) JobSettings {
return JobSettings{Name: name}
}
// WithFields adds new event fields to a Job. Existing fields will be
// overwritten.
// The fields map will be updated (no copy).
func (s JobSettings) WithFields(m common.MapStr) JobSettings {
s.AddFields(m)
return s
}
// AddFields adds new event fields to a Job. Existing fields will be
// overwritten.
func (s *JobSettings) AddFields(m common.MapStr) { addFields(&s.Fields, m) }
// MakeHostJobSettings creates a new HostJobSettings structure without any global
// event fields.
func MakeHostJobSettings(name, host string, ip IPSettings) HostJobSettings {
return HostJobSettings{Name: name, Host: host, IP: ip}
}
// WithFields adds new event fields to a Job. Existing fields will be
// overwritten.
// The fields map will be updated (no copy).
func (s HostJobSettings) WithFields(m common.MapStr) HostJobSettings {
s.AddFields(m)
return s
}
// AddFields adds new event fields to a Job. Existing fields will be
// overwritten.
func (s *HostJobSettings) AddFields(m common.MapStr) { addFields(&s.Fields, m) }
func addFields(to *common.MapStr, m common.MapStr) {
if m == nil {
return
}
fields := *to
if fields == nil {
fields = common.MapStr{}
*to = fields
}
fields.DeepUpdate(m)
}
func (s *HostJobSettings) jobSettings() JobSettings {
return JobSettings{Name: s.Name, Fields: s.Fields}
}