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