Skip to content

Commit

Permalink
Merge pull request #722 from Meepoljdx/main
Browse files Browse the repository at this point in the history
add: add timeout config for ntp input plugin
  • Loading branch information
kongfei605 authored Dec 5, 2023
2 parents 7c86395 + 51b261b commit 1a00123
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 3 deletions.
3 changes: 3 additions & 0 deletions conf/input.ntp/ntp.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@

# # ntp servers
# ntp_servers = ["ntp.aliyun.com"]

# # response time out seconds
# timeout = 5
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ require (
github.com/prometheus/prometheus v0.37.0
github.com/shirou/gopsutil/v3 v3.22.5
github.com/sirupsen/logrus v1.8.1 // indirect
github.com/toolkits/pkg v1.3.7
github.com/stretchr/testify v1.8.4
github.com/toolkits/pkg v1.3.5
github.com/ulricqin/gosnmp v0.0.1
github.com/xdg/scram v1.0.5
go.mongodb.org/mongo-driver v1.9.1
Expand Down
9 changes: 7 additions & 2 deletions inputs/ntp/ntp.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"flashcat.cloud/categraf/config"
"flashcat.cloud/categraf/inputs"
"flashcat.cloud/categraf/types"

"github.com/toolkits/pkg/nux"
)

Expand All @@ -15,12 +16,16 @@ const inputName = "ntp"
type NTPStat struct {
config.PluginConfig
NTPServers []string `toml:"ntp_servers"`
TimeOut int64 `toml:"timeout"`
server string
}

func init() {
inputs.Add(inputName, func() inputs.Input {
return &NTPStat{}
return &NTPStat{
// default timeout is 5 seconds
TimeOut: 5,
}
})
}

Expand All @@ -46,7 +51,7 @@ func (n *NTPStat) Gather(slist *types.SampleList) {
}

orgTime := time.Now()
serverReciveTime, serverTransmitTime, err := nux.NtpTwoTime(n.server)
serverReciveTime, serverTransmitTime, err := nux.NtpTwoTime(n.server, n.TimeOut)
if err != nil {
log.Println("E! failed to connect ntp server:", n.server, "error:", err)
n.server = ""
Expand Down
26 changes: 26 additions & 0 deletions inputs/ntp/ntp_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package ntp

import (
"log"
"testing"
"time"

"github.com/toolkits/pkg/nux"
)

func TestGetTwoTime(t *testing.T) {
orgTime := time.Now()
log.Println("Begin")
serverReciveTime, serverTransmitTime, err := nux.NtpTwoTime("ntp1.aliyun.com", 20)
if err != nil {
log.Println(err)
return
}
dstTime := time.Now()

// https://en.wikipedia.org/wiki/Network_Time_Protocol
duration := ((serverReciveTime.UnixNano() - orgTime.UnixNano()) + (serverTransmitTime.UnixNano() - dstTime.UnixNano())) / 2

delta := duration / 1e6 // convert to ms
log.Println(delta)
}

0 comments on commit 1a00123

Please sign in to comment.