fix(inputs.ntpq): Avoid panic on empty lines and make sure -p is present (#16110)

This commit is contained in:
Sven Rebhan 2024-11-04 22:56:27 +01:00 committed by GitHub
parent 85f025ad22
commit 115df09b19
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 14 additions and 4 deletions

View File

@ -9,13 +9,13 @@ import (
"math/bits" "math/bits"
"os/exec" "os/exec"
"regexp" "regexp"
"slices"
"strconv" "strconv"
"strings" "strings"
"github.com/kballard/go-shellquote" "github.com/kballard/go-shellquote"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal/choice"
"github.com/influxdata/telegraf/plugins/inputs" "github.com/influxdata/telegraf/plugins/inputs"
) )
@ -87,10 +87,13 @@ func (n *NTPQ) Init() error {
return fmt.Errorf("splitting options failed: %w", err) return fmt.Errorf("splitting options failed: %w", err)
} }
if !n.DNSLookup { if !n.DNSLookup {
if !choice.Contains("-n", options) { if !slices.Contains(options, "-n") {
options = append(options, "-n") options = append(options, "-n")
} }
} }
if !slices.Contains(options, "-p") {
options = append(options, "-p")
}
n.runQ = func(server string) ([]byte, error) { n.runQ = func(server string) ([]byte, error) {
bin, err := exec.LookPath("ntpq") bin, err := exec.LookPath("ntpq")
@ -99,7 +102,7 @@ func (n *NTPQ) Init() error {
} }
// Needs to be last argument // Needs to be last argument
var args []string args := make([]string, 0, len(options)+1)
args = append(args, options...) args = append(args, options...)
if server != "" { if server != "" {
args = append(args, server) args = append(args, server)
@ -159,6 +162,10 @@ func (n *NTPQ) gatherServer(acc telegraf.Accumulator, server string) {
for scanner.Scan() { for scanner.Scan() {
line := scanner.Text() line := scanner.Text()
if line == "" {
continue
}
_, elements := processLine(line) _, elements := processLine(line)
if len(elements) < 2 { if len(elements) < 2 {
continue continue
@ -191,6 +198,10 @@ func (n *NTPQ) gatherServer(acc telegraf.Accumulator, server string) {
for scanner.Scan() { for scanner.Scan() {
line := scanner.Text() line := scanner.Text()
if line == "" {
continue
}
prefix, elements := processLine(line) prefix, elements := processLine(line)
if len(elements) != len(columns) { if len(elements) != len(columns) {
continue continue
@ -298,7 +309,6 @@ func init() {
inputs.Add("ntpq", func() telegraf.Input { inputs.Add("ntpq", func() telegraf.Input {
return &NTPQ{ return &NTPQ{
DNSLookup: true, DNSLookup: true,
Options: "-p",
} }
}) })
} }