forked from grafana/synthetic-monitoring-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
icmp.go
110 lines (84 loc) · 2.28 KB
/
icmp.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
package icmp
import (
"context"
"errors"
"sync"
"time"
"github.com/dzacball/synthetic-monitoring-agent/misizonsniper/prober/logger"
sm "github.com/dzacball/synthetic-monitoring-agent/pkg/pb/synthetic_monitoring"
"github.com/go-kit/log"
"github.com/prometheus/blackbox_exporter/config"
"github.com/prometheus/client_golang/prometheus"
)
var errUnsupportedCheck = errors.New("unsupported check")
type Module struct {
Prober string
Timeout time.Duration
PacketCount int64
ICMP config.ICMPProbe
Privileged bool
}
type Prober struct {
config Module
}
func NewProber(check sm.Check) (Prober, error) {
var p Prober
if check.Settings.Ping == nil {
return p, errUnsupportedCheck
}
p.config = settingsToModule(check.Settings.Ping)
p.config.Timeout = time.Duration(check.Timeout) * time.Millisecond
p.config.Privileged = isPrivilegedRequired()
return p, nil
}
func (p Prober) Name() string {
return "ping"
}
func (p Prober) Probe(ctx context.Context, target string, registry *prometheus.Registry, logger logger.Logger) bool {
return probeICMP(ctx, target, p.config, registry, logger)
}
func settingsToModule(settings *sm.PingSettings) Module {
var m Module
m.Prober = sm.CheckTypePing.String()
m.ICMP.IPProtocol, m.ICMP.IPProtocolFallback = settings.IpVersion.ToIpProtocol()
m.ICMP.SourceIPAddress = settings.SourceIpAddress
m.ICMP.PayloadSize = int(settings.PayloadSize)
m.ICMP.DontFragment = settings.DontFragment
if settings.PacketCount <= 1 {
m.PacketCount = 1
} else {
m.PacketCount = settings.PacketCount
}
return m
}
var (
privilegedRequired bool
privilegedCheckDone bool
privilegedCheckMutex sync.Mutex
)
func isPrivilegedRequired() bool {
privilegedCheckMutex.Lock()
defer privilegedCheckMutex.Unlock()
if privilegedCheckDone {
return privilegedRequired
}
var (
ctx = context.Background()
target = "127.0.0.1"
registry = prometheus.NewRegistry()
logger = log.NewNopLogger()
config = Module{
Prober: "test-unprivileged",
Timeout: 1 * time.Second,
PacketCount: 1,
Privileged: false,
ICMP: config.ICMPProbe{
IPProtocol: "ip4",
},
}
)
success := probeICMP(ctx, target, config, registry, logger)
privilegedRequired = !success
privilegedCheckDone = true
return privilegedRequired
}