From 513346045520959e400dff2e3660d5f7a84d0e16 Mon Sep 17 00:00:00 2001 From: Ahmet Ozturk Date: Wed, 11 Nov 2026 15:40:12 +0100 Subject: [PATCH 1/2] check_ping: use iphlpapi instead of ping.exe on Windows Replace the ping.exe call and localized output parser on Windows with the unprivileged ICMP echo API from iphlpapi.dll: - IPv4 uses IcmpCreateFile/IcmpSendEcho, IPv6 uses Icmp6CreateFile/Icmp6SendEcho2. - No child process and no locale-dependent output parsing. - Send one echo per second, using the per-packet timeout from -t or the 4 second default. The overall runtime is capped by the check deadline. - Keep packet results indexed so timeouts and out-of-order completions retain their packet position. - Write rta and pl with %.3f. IPv4 replies provide ttl; the IPv6 reply structure has no ttl field. - Reject -4 together with -6 and non-positive packet counts. The ping.exe parser is unchanged for Linux, macOS and FreeBSD. Add a build-tagged Windows implementation and a non-Windows stub. Add tests for the ICMP reply layouts, IP status mapping, result aggregation, indexed reply collection and IcmpCreateFile availability. The live check_ping test now accepts the %.3f packet loss output. --- pkg/snclient/check_ping.go | 31 -- pkg/snclient/check_ping_other.go | 12 + pkg/snclient/check_ping_test.go | 2 +- pkg/snclient/check_ping_windows.go | 414 ++++++++++++++++++++++++ pkg/snclient/check_ping_windows_test.go | 111 +++++++ 5 files changed, 538 insertions(+), 32 deletions(-) create mode 100644 pkg/snclient/check_ping_other.go create mode 100644 pkg/snclient/check_ping_windows.go create mode 100644 pkg/snclient/check_ping_windows_test.go diff --git a/pkg/snclient/check_ping.go b/pkg/snclient/check_ping.go index 7194f041..56744a79 100644 --- a/pkg/snclient/check_ping.go +++ b/pkg/snclient/check_ping.go @@ -140,37 +140,6 @@ func (l *CheckPing) addPingLinux(ctx context.Context, check *CheckData) error { return nil } -// run ping command on windows -func (l *CheckPing) addPingWindows(ctx context.Context, check *CheckData) error { - cmd := fmt.Sprintf("ping.exe -n %d", l.packets) - if l.ipv4 { - cmd += " -4" - } - if l.ipv6 { - cmd += " -6" - } - if l.timeout > 0 { - cmd += fmt.Sprintf(" -w %d", l.timeout*1000) - } - cmd += fmt.Sprintf(" '%s'", l.hostname) - - command, err := l.snc.MakeCmd(ctx, cmd) - if err != nil { - return err - } - - output, stderr, _, _, err := l.snc.runExternalCommand(ctx, command, check.timeout-(1*time.Second)) - if err != nil { - return fmt.Errorf("ping failed: %s\n%s", err.Error(), stderr) - } - - entry := l.parsePingOutput(output, stderr) - check.listData = append(check.listData, entry) - l.addMetrics(check, entry) - - return nil -} - func (l *CheckPing) parsePingOutput(output, stderr string) (entry map[string]string) { entry = l.defaultEntry() diff --git a/pkg/snclient/check_ping_other.go b/pkg/snclient/check_ping_other.go new file mode 100644 index 00000000..4d765fdf --- /dev/null +++ b/pkg/snclient/check_ping_other.go @@ -0,0 +1,12 @@ +//go:build !windows + +package snclient + +import ( + "context" + "fmt" +) + +func (l *CheckPing) addPingWindows(_ context.Context, _ *CheckData) error { + return fmt.Errorf("ping is not supported on this platform") +} diff --git a/pkg/snclient/check_ping_test.go b/pkg/snclient/check_ping_test.go index a2c47ed4..681e6837 100644 --- a/pkg/snclient/check_ping_test.go +++ b/pkg/snclient/check_ping_test.go @@ -20,7 +20,7 @@ CheckBuiltinPlugins = enabled res = snc.RunCheck("check_ping", []string{"host=10.99.99.99", "packets=2", "-t", "1"}) assert.Equalf(t, CheckExitCritical, res.State, "state critical") - assert.Regexpf(t, `^CRITICAL - Packet loss = 100(|\.0)% \|'rta'=U 'pl'=100%;30;80;0`, string(res.BuildPluginOutput()), "output matches") + assert.Regexpf(t, `^CRITICAL - Packet loss = 100(\.0+)?% \|'rta'=U 'pl'=100%;30;80;0`, string(res.BuildPluginOutput()), "output matches") res = snc.RunCheck("check_ping", []string{"host=should_not_resolve.nowhere", "packets=1"}) assert.Equalf(t, CheckExitUnknown, res.State, "state unknown") diff --git a/pkg/snclient/check_ping_windows.go b/pkg/snclient/check_ping_windows.go new file mode 100644 index 00000000..5048c186 --- /dev/null +++ b/pkg/snclient/check_ping_windows.go @@ -0,0 +1,414 @@ +//go:build windows + +package snclient + +import ( + "context" + "encoding/binary" + "errors" + "fmt" + "net" + "strconv" + "sync" + "syscall" + "time" + "unsafe" + + "golang.org/x/sys/windows" +) + +const ( + icmpDefaultTimeout = 4 * time.Second // ping.exe default + icmpPacketSize = 32 // ping.exe default payload + icmpSendInterval = time.Second + icmpReplySlack = 24 // ICMP error message and IO_STATUS_BLOCK , extend the buffer by this much + + ipSuccess = 0 + ipStatusMin = 11001 // IP_BUF_TOO_SMALL + ipStatusMax = 11045 // IP_DEST_SCOPE_MISMATCH, the last IPv6 status + ipReqTimedOut = 11010 + ipGeneralFailure = 11050 +) + +var ( + iphlpapiDLL = windows.NewLazySystemDLL("iphlpapi.dll") + + procIcmpCreateFile = iphlpapiDLL.NewProc("IcmpCreateFile") + procIcmpCloseHandle = iphlpapiDLL.NewProc("IcmpCloseHandle") + procIcmpSendEcho = iphlpapiDLL.NewProc("IcmpSendEcho") + procIcmp6CreateFile = iphlpapiDLL.NewProc("Icmp6CreateFile") + procIcmp6SendEcho2 = iphlpapiDLL.NewProc("Icmp6SendEcho2") + + loadICMPOnce sync.Once + errLoadICMP error +) + +// ipOptionInformation mirrors IP_OPTION_INFORMATION (ipexport.h). +type ipOptionInformation struct { + TTL uint8 + TOS uint8 + Flags uint8 + OptionsSize uint8 + OptionsData uintptr +} + +// icmpEchoReply mirrors ICMP_ECHO_REPLY (ipexport.h). +// IcmpSendEcho parses the reply buffer itself, so the native layout is used on 64 bit as well. +type icmpEchoReply struct { + Address uint32 + Status uint32 + RoundTripTime uint32 + DataSize uint16 + Reserved uint16 + Data uintptr + Options ipOptionInformation +} + +// icmpv6EchoReply mirrors ICMPV6_ECHO_REPLY (ipexport.h). +// Its IPV6_ADDRESS_EX prefix is packed and 26 bytes long, so Status starts at offset 28. +// Unlike IPv4, the API returns no TTL for IPv6. +type icmpv6EchoReply struct { + Address [26]byte + _ [2]byte + Status uint32 + RoundTripTime uint32 +} + +type pingReply struct { + rtt uint32 + ttl uint8 + status uint32 + err error +} + +type indexedPingReply struct { + index int + reply pingReply +} + +// loadICMP checks that iphlpapi.dll exports every function this file calls. +func loadICMP() error { + loadICMPOnce.Do(func() { + for _, proc := range []*windows.LazyProc{ + procIcmpCreateFile, procIcmpCloseHandle, procIcmpSendEcho, + procIcmp6CreateFile, procIcmp6SendEcho2, + } { + if err := proc.Find(); err != nil { + errLoadICMP = fmt.Errorf("iphlpapi.dll: %w", err) + + return + } + } + }) + + return errLoadICMP +} + +func (l *CheckPing) addPingWindows(ctx context.Context, check *CheckData) error { + if l.ipv4 && l.ipv6 { + return fmt.Errorf("cannot use -4 and -6 together") + } + if l.packets < 1 { + return fmt.Errorf("packets must be greater than 0") + } + if err := loadICMP(); err != nil { + return err + } + + ips, err := l.resolvePingHost(ctx) + if err != nil { + if ctx.Err() != nil { + return fmt.Errorf("ping: %w", ctx.Err()) + } + + return l.addPingResolveError(check) + } + + perPacket := icmpDefaultTimeout + if l.timeout > 0 { + perPacket = time.Duration(l.timeout) * time.Second + } + + // Leave one second for the check to finalize, like the command variant. + pingCtx, cancel := context.WithDeadline(ctx, time.Now().Add(check.timeout-time.Second)) + defer cancel() + + results := l.pingAddress(pingCtx, ips[0], perPacket) + entry, err := l.pingEntry(results) + if err != nil { + return err + } + + check.listData = append(check.listData, entry) + l.addMetrics(check, entry) + + return nil +} + +// resolvePingHost returns the addresses in resolver order. +// This matches the address family ping.exe would use. +func (l *CheckPing) resolvePingHost(ctx context.Context) ([]net.IP, error) { + network := "ip" + switch { + case l.ipv4: + network = "ip4" + case l.ipv6: + network = "ip6" + } + + ips, err := net.DefaultResolver.LookupIP(ctx, network, l.hostname) + if err != nil { + return nil, fmt.Errorf("failed to resolve hostname: %w", err) + } + if len(ips) == 0 { + return nil, fmt.Errorf("failed to resolve hostname") + } + + return ips, nil +} + +func (l *CheckPing) addPingResolveError(check *CheckData) error { + entry := l.defaultEntry() + entry["_error"] = "failed to resolve hostname" + entry["pl"] = fmt.Sprintf("%.3f", 100.0) + check.listData = append(check.listData, entry) + l.addMetrics(check, entry) + + return nil +} + +// pingAddress sends one echo per second, like ping.exe. +// Every packet runs in its own goroutine because IcmpSendEcho is synchronous. +func (l *CheckPing) pingAddress(ctx context.Context, address net.IP, perPacket time.Duration) []pingReply { + packets := int(l.packets) + replies := make(chan indexedPingReply, packets) + sent := 0 + + ticker := time.NewTicker(icmpSendInterval) + defer ticker.Stop() + + for sent < packets { + if sent > 0 { + select { + case <-ticker.C: + case <-ctx.Done(): // ctx has a timeout based on check.timeout + return collectPingReplies(replies, sent, packets, ctx.Err()) + } + } + + index := sent + go func() { + replies <- indexedPingReply{ + index: index, + reply: l.pingOnce(ctx, address, perPacket), + } + }() + sent++ + } + + return collectPingReplies(replies, sent, packets, nil) +} + +func collectPingReplies(replies <-chan indexedPingReply, sent, packets int, err error) []pingReply { + results := make([]pingReply, packets) + for i := range results { + results[i] = pingReply{status: ipReqTimedOut} + } + if err != nil { + for i := sent; i < packets; i++ { + results[i] = pingReply{err: err} + } + } + + for range sent { + result := <-replies + results[result.index] = result.reply + } + + return results +} + +func (l *CheckPing) pingOnce(ctx context.Context, address net.IP, perPacket time.Duration) pingReply { + select { + case <-ctx.Done(): + return pingReply{err: ctx.Err()} + default: + } + + timeout := perPacket + if deadline, ok := ctx.Deadline(); ok { + if remaining := time.Until(deadline); remaining < timeout { + timeout = remaining + } + } + if timeout <= 0 { + return pingReply{status: ipReqTimedOut} + } + + if address.To4() != nil { + rtt, ttl, status, err := icmpEcho4(address, timeout) + + return pingReply{rtt: rtt, ttl: ttl, status: status, err: err} + } + + rtt, ttl, status, err := icmpEcho6(address, timeout) + + return pingReply{rtt: rtt, ttl: ttl, status: status, err: err} +} + +func (l *CheckPing) pingEntry(results []pingReply) (map[string]string, error) { + entry := l.defaultEntry() + sent := int(l.packets) + received := 0 + var rttSum uint64 + var ttl uint8 + var firstErr error + + for _, result := range results { + switch { + case result.err != nil: + if firstErr == nil { + firstErr = result.err + } + case result.status == ipSuccess: + received++ + rttSum += uint64(result.rtt) + if ttl == 0 { + ttl = result.ttl + } + } + } + + if received == 0 && firstErr != nil { + return nil, fmt.Errorf("ping failed: %w", firstErr) + } + if firstErr != nil { + log.Debugf("ping: %s", firstErr) + } + + entry["sent"] = strconv.Itoa(sent) + entry["received"] = strconv.Itoa(received) + entry["pl"] = fmt.Sprintf("%.3f", float64(sent-received)*100/float64(sent)) + if received > 0 { + rta := float64(rttSum) / float64(received) + entry["rta"] = fmt.Sprintf("%.3f", rta) + if ttl > 0 { + entry["ttl"] = strconv.Itoa(int(ttl)) + } + } + + return entry, nil +} + +func icmpEcho4(address net.IP, timeout time.Duration) (rtt uint32, ttl uint8, status uint32, err error) { + handle, _, callErr := procIcmpCreateFile.Call() + if handle == 0 || windows.Handle(handle) == windows.InvalidHandle { + return 0, 0, 0, fmt.Errorf("IcmpCreateFile: %w", callErr) + } + defer procIcmpCloseHandle.Call(handle) //nolint:errcheck // a close failure cannot be handled + + ip4 := address.To4() + if ip4 == nil { + return 0, 0, 0, fmt.Errorf("not an IPv4 address: %s", address) + } + + payload := make([]byte, icmpPacketSize) + buf := make([]byte, int(unsafe.Sizeof(icmpEchoReply{}))+len(payload)+icmpReplySlack) + + count, _, callErr := procIcmpSendEcho.Call( + handle, + uintptr(binary.LittleEndian.Uint32(ip4)), + uintptr(unsafe.Pointer(&payload[0])), + uintptr(len(payload)), + 0, + uintptr(unsafe.Pointer(&buf[0])), + uintptr(len(buf)), + icmpTimeoutMillis(timeout), + ) + if count == 0 { + if ipStatus, ok := icmpStatusFromError(callErr); ok { + return 0, 0, ipStatus, nil + } + + return 0, 0, 0, fmt.Errorf("IcmpSendEcho: %w", callErr) + } + + reply := (*icmpEchoReply)(unsafe.Pointer(&buf[0])) + + return reply.RoundTripTime, reply.Options.TTL, reply.Status, nil +} + +func icmpEcho6(address net.IP, timeout time.Duration) (rtt uint32, ttl uint8, status uint32, err error) { + handle, _, callErr := procIcmp6CreateFile.Call() + if handle == 0 || windows.Handle(handle) == windows.InvalidHandle { + return 0, 0, 0, fmt.Errorf("Icmp6CreateFile: %w", callErr) + } + defer procIcmpCloseHandle.Call(handle) //nolint:errcheck // a close failure cannot be handled + + ip16 := address.To16() + if ip16 == nil { + return 0, 0, 0, fmt.Errorf("not an IPv6 address: %s", address) + } + + var source, destination windows.RawSockaddrInet6 + source.Family = windows.AF_INET6 + destination.Family = windows.AF_INET6 + copy(destination.Addr[:], ip16) + + payload := make([]byte, icmpPacketSize) + buf := make([]byte, int(unsafe.Sizeof(icmpv6EchoReply{}))+len(payload)+icmpReplySlack) + + count, _, callErr := procIcmp6SendEcho2.Call( + handle, + 0, // Event + 0, // ApcRoutine + 0, // ApcContext + uintptr(unsafe.Pointer(&source)), + uintptr(unsafe.Pointer(&destination)), + uintptr(unsafe.Pointer(&payload[0])), + uintptr(len(payload)), + 0, // RequestOptions + uintptr(unsafe.Pointer(&buf[0])), + uintptr(len(buf)), + icmpTimeoutMillis(timeout), + ) + if count == 0 { + if ipStatus, ok := icmpStatusFromError(callErr); ok { + return 0, 0, ipStatus, nil + } + + return 0, 0, 0, fmt.Errorf("Icmp6SendEcho2: %w", callErr) + } + + reply := (*icmpv6EchoReply)(unsafe.Pointer(&buf[0])) + + return reply.RoundTripTime, 0, reply.Status, nil +} + +// icmpStatusFromError returns the IP_STATUS in a failed echo call. +// A timeout and an unreachable destination are packet loss, not a broken check. +func icmpStatusFromError(err error) (uint32, bool) { + var errno syscall.Errno + if !errors.As(err, &errno) { + return 0, false + } + if errno == 0 { + return ipGeneralFailure, true + } + + status := uint32(errno) + switch { + case status >= ipStatusMin && status <= ipStatusMax: + return status, true + case status == ipGeneralFailure: + return status, true + default: + return 0, false + } +} + +func icmpTimeoutMillis(timeout time.Duration) uintptr { + millis := max(timeout.Milliseconds(), 1) + + return uintptr(millis) +} diff --git a/pkg/snclient/check_ping_windows_test.go b/pkg/snclient/check_ping_windows_test.go new file mode 100644 index 00000000..0ee0471c --- /dev/null +++ b/pkg/snclient/check_ping_windows_test.go @@ -0,0 +1,111 @@ +//go:build windows + +package snclient + +import ( + "context" + "errors" + "fmt" + "syscall" + "testing" + "unsafe" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "golang.org/x/sys/windows" +) + +func TestICMPReplyLayout(t *testing.T) { + var reply4 icmpEchoReply + var reply6 icmpv6EchoReply + + if unsafe.Sizeof(uintptr(0)) == 8 { + assert.Equal(t, uintptr(40), unsafe.Sizeof(reply4)) + assert.Equal(t, uintptr(24), unsafe.Offsetof(reply4.Options)) + assert.Equal(t, uintptr(0), unsafe.Offsetof(reply4.Options.TTL)) + assert.Equal(t, uintptr(8), unsafe.Offsetof(reply4.Options.OptionsData)) + + assert.Equal(t, uintptr(36), unsafe.Sizeof(reply6)) + assert.Equal(t, uintptr(28), unsafe.Offsetof(reply6.Status)) + assert.Equal(t, uintptr(32), unsafe.Offsetof(reply6.RoundTripTime)) + + return + } + + assert.Equal(t, uintptr(28), unsafe.Sizeof(reply4)) + assert.Equal(t, uintptr(20), unsafe.Offsetof(reply4.Options)) + assert.Equal(t, uintptr(0), unsafe.Offsetof(reply4.Options.TTL)) + assert.Equal(t, uintptr(4), unsafe.Offsetof(reply4.Options.OptionsData)) + + assert.Equal(t, uintptr(36), unsafe.Sizeof(reply6)) + assert.Equal(t, uintptr(28), unsafe.Offsetof(reply6.Status)) + assert.Equal(t, uintptr(32), unsafe.Offsetof(reply6.RoundTripTime)) +} + +func TestPingEntry(t *testing.T) { + chk := &CheckPing{packets: 4} + + entry, err := chk.pingEntry([]pingReply{ + {rtt: 2, ttl: 128, status: ipSuccess}, + {rtt: 4, ttl: 64, status: ipSuccess}, + {status: ipReqTimedOut}, + {err: errors.New("icmp failed")}, + }) + require.NoError(t, err) + assert.Equal(t, "4", entry["sent"]) + assert.Equal(t, "2", entry["received"]) + assert.Equal(t, "50.000", entry["pl"]) + assert.Equal(t, "3.000", entry["rta"]) + assert.Equal(t, "128", entry["ttl"]) + + entry, err = chk.pingEntry([]pingReply{ + {status: ipReqTimedOut}, + {status: ipReqTimedOut}, + {status: ipReqTimedOut}, + {status: ipReqTimedOut}, + }) + require.NoError(t, err) + assert.Equal(t, "100.000", entry["pl"]) + assert.Empty(t, entry["rta"]) + assert.Empty(t, entry["ttl"]) + + _, err = chk.pingEntry([]pingReply{{err: errors.New("icmp failed")}}) + assert.Error(t, err) +} + +func TestCollectPingReplies(t *testing.T) { + replies := make(chan indexedPingReply, 2) + replies <- indexedPingReply{index: 1, reply: pingReply{status: ipSuccess, rtt: 5}} + replies <- indexedPingReply{index: 0, reply: pingReply{status: ipReqTimedOut}} + + results := collectPingReplies(replies, 2, 3, context.Canceled) + require.Len(t, results, 3) + assert.Equal(t, uint32(ipReqTimedOut), results[0].status) + assert.Equal(t, uint32(ipSuccess), results[1].status) + assert.Equal(t, uint32(5), results[1].rtt) + assert.ErrorIs(t, results[2].err, context.Canceled) +} + +func TestICMPStatusFromError(t *testing.T) { + status, ok := icmpStatusFromError(syscall.Errno(ipReqTimedOut)) + assert.True(t, ok) + assert.Equal(t, uint32(ipReqTimedOut), status) + + status, ok = icmpStatusFromError(fmt.Errorf("wrapped: %w", syscall.Errno(11003))) + assert.True(t, ok) + assert.Equal(t, uint32(11003), status) + + _, ok = icmpStatusFromError(syscall.Errno(5)) + assert.False(t, ok) +} + +func TestICMPCreateFile(t *testing.T) { + require.NoError(t, loadICMP()) + + handle, _, callErr := procIcmpCreateFile.Call() + if !assert.False(t, handle == 0 || windows.Handle(handle) == windows.InvalidHandle, + "IcmpCreateFile failed: %v", callErr) { + return + } + procIcmpCloseHandle.Call(handle) //nolint:errcheck // test cleanup +} From 0419f3002adf71e2c369ca910a82eed984c98a33 Mon Sep 17 00:00:00 2001 From: Ahmet Ozturk Date: Wed, 11 Nov 2026 15:50:35 +0100 Subject: [PATCH 2/2] check_ping: clamp packet count to maximum of 1000 this is to prevent big slice allocation if a user wants absurdly high packet number. sending 1000 packets should take around 16 minutes already. --- docs/checks/commands/check_ping.md | 14 +++++++------- pkg/snclient/check_ping.go | 13 ++++++++++++- pkg/snclient/check_ping_test.go | 14 ++++++++++++++ pkg/snclient/check_ping_windows.go | 5 +++-- 4 files changed, 36 insertions(+), 10 deletions(-) diff --git a/docs/checks/commands/check_ping.md b/docs/checks/commands/check_ping.md index 0e141655..1becbbec 100644 --- a/docs/checks/commands/check_ping.md +++ b/docs/checks/commands/check_ping.md @@ -30,13 +30,13 @@ Checks the ICMP ping connection. ## Check Specific Arguments -| Argument | Description | -| -------- | ------------------------------------------------ | -| -4 | Force using IPv4. | -| -6 | Force using IPv6. | -| -t | timeout in seconds for each ICMP ECHO packet | -| host | host name or IP address to ping | -| packets | number of ICMP ECHO packets to send (default: 5) | +| Argument | Description | +| -------- | ----------------------------------------------------------- | +| -4 | Force using IPv4. | +| -6 | Force using IPv6. | +| -t | timeout in seconds for each ICMP ECHO packet | +| host | host name or IP address to ping | +| packets | number of ICMP ECHO packets to send (default: 5, max: 1000) | ## Attributes diff --git a/pkg/snclient/check_ping.go b/pkg/snclient/check_ping.go index 56744a79..85101d38 100644 --- a/pkg/snclient/check_ping.go +++ b/pkg/snclient/check_ping.go @@ -15,6 +15,8 @@ func init() { AvailableChecks["check_ping"] = CheckEntry{"check_ping", NewCheckPing} } +const maxPingPackets = 1000 + type CheckPing struct { snc *Agent hostname string @@ -41,7 +43,7 @@ func (l *CheckPing) Build() *CheckData { }, args: map[string]CheckArgument{ "host": {value: &l.hostname, description: "host name or IP address to ping"}, - "packets": {value: &l.packets, description: "number of ICMP ECHO packets to send (default: 5)"}, + "packets": {value: &l.packets, description: "number of ICMP ECHO packets to send (default: 5, max: 1000)"}, "-t": {value: &l.timeout, description: "timeout in seconds for each ICMP ECHO packet"}, "-4": {value: &l.ipv4, description: "Force using IPv4."}, "-6": {value: &l.ipv6, description: "Force using IPv6."}, @@ -79,6 +81,8 @@ func (l *CheckPing) Check(ctx context.Context, snc *Agent, check *CheckData, _ [ return nil, fmt.Errorf("host name must not contain nasty characters") } + l.clampPackets() + err := l.addSources(ctx, check) if err != nil { return nil, err @@ -87,6 +91,13 @@ func (l *CheckPing) Check(ctx context.Context, snc *Agent, check *CheckData, _ [ return check.Finalize() } +func (l *CheckPing) clampPackets() { + if l.packets > maxPingPackets { + log.Warnf("check_ping: packets=%d exceeds the maximum of %d, using %d", l.packets, maxPingPackets, maxPingPackets) + l.packets = maxPingPackets + } +} + func (l *CheckPing) addSources(ctx context.Context, check *CheckData) (err error) { switch runtime.GOOS { case "linux", "darwin", "freebsd": diff --git a/pkg/snclient/check_ping_test.go b/pkg/snclient/check_ping_test.go index 681e6837..401c7c62 100644 --- a/pkg/snclient/check_ping_test.go +++ b/pkg/snclient/check_ping_test.go @@ -6,6 +6,20 @@ import ( "github.com/stretchr/testify/assert" ) +func TestPingPacketCap(t *testing.T) { + chk := &CheckPing{packets: maxPingPackets + 1} + chk.clampPackets() + assert.Equal(t, int64(maxPingPackets), chk.packets) + + chk.packets = maxPingPackets + chk.clampPackets() + assert.Equal(t, int64(maxPingPackets), chk.packets) + + chk.packets = 5 + chk.clampPackets() + assert.Equal(t, int64(5), chk.packets) +} + func TestCheckPing(t *testing.T) { config := ` [/modules] diff --git a/pkg/snclient/check_ping_windows.go b/pkg/snclient/check_ping_windows.go index 5048c186..a9523c06 100644 --- a/pkg/snclient/check_ping_windows.go +++ b/pkg/snclient/check_ping_windows.go @@ -21,7 +21,8 @@ const ( icmpDefaultTimeout = 4 * time.Second // ping.exe default icmpPacketSize = 32 // ping.exe default payload icmpSendInterval = time.Second - icmpReplySlack = 24 // ICMP error message and IO_STATUS_BLOCK , extend the buffer by this much + icmpReplySlack = 24 // ICMP error message and IO_STATUS_BLOCK + icmpPacketLossMax = 100 // complete packet loss in percent ipSuccess = 0 ipStatusMin = 11001 // IP_BUF_TOO_SMALL @@ -170,7 +171,7 @@ func (l *CheckPing) resolvePingHost(ctx context.Context) ([]net.IP, error) { func (l *CheckPing) addPingResolveError(check *CheckData) error { entry := l.defaultEntry() entry["_error"] = "failed to resolve hostname" - entry["pl"] = fmt.Sprintf("%.3f", 100.0) + entry["pl"] = fmt.Sprintf("%.3f", float64(icmpPacketLossMax)) check.listData = append(check.listData, entry) l.addMetrics(check, entry)