-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
ntp.go
253 lines (208 loc) · 6.81 KB
/
ntp.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
//nolint:revive // TODO(PLINT) Fix revive linter
package ntp
import (
"context"
"expvar"
"fmt"
"math"
"sort"
"strings"
"time"
"github.com/beevik/ntp"
"gopkg.in/yaml.v2"
"github.com/DataDog/datadog-agent/comp/core/autodiscovery/integration"
"github.com/DataDog/datadog-agent/pkg/aggregator/sender"
"github.com/DataDog/datadog-agent/pkg/collector/check"
core "github.com/DataDog/datadog-agent/pkg/collector/corechecks"
"github.com/DataDog/datadog-agent/pkg/metrics/servicecheck"
"github.com/DataDog/datadog-agent/pkg/telemetry"
"github.com/DataDog/datadog-agent/pkg/util/cloudproviders"
"github.com/DataDog/datadog-agent/pkg/util/log"
"github.com/DataDog/datadog-agent/pkg/util/optional"
)
const (
// CheckName is the name of the check
CheckName = "ntp"
defaultMinCollectionInterval = 900 // 15 minutes, to follow pool.ntp.org's guidelines on the query rate
)
var (
ntpExpVar = expvar.NewFloat("ntpOffset")
// for testing purpose
ntpQuery = ntp.QueryWithOptions
tlmNtpOffset = telemetry.NewGauge("check", "ntp_offset",
nil, "Ntp offset")
defaultDatadogPool = []string{"0.datadog.pool.ntp.org", "1.datadog.pool.ntp.org", "2.datadog.pool.ntp.org", "3.datadog.pool.ntp.org"}
)
// NTPCheck only has sender and config
type NTPCheck struct {
core.CheckBase
cfg *ntpConfig
lastCollection time.Time
}
type ntpInstanceConfig struct {
OffsetThreshold int `yaml:"offset_threshold"`
Host string `yaml:"host"`
Hosts []string `yaml:"hosts"`
Port int `yaml:"port"`
Timeout int `yaml:"timeout"`
Version int `yaml:"version"`
UseLocalDefinedServers bool `yaml:"use_local_defined_servers"`
}
type ntpInitConfig struct{}
type ntpConfig struct {
instance ntpInstanceConfig
initConf ntpInitConfig
}
func (c *NTPCheck) String() string {
return "ntp"
}
// for testing
var getCloudProviderNTPHosts = cloudproviders.GetCloudProviderNTPHosts
func (c *ntpConfig) parse(data []byte, initData []byte, getLocalServers func() ([]string, error)) error {
var instance ntpInstanceConfig
var initConf ntpInitConfig
defaultVersion := 3
defaultTimeout := 5
defaultPort := 123
defaultOffsetThreshold := 60
defaultHosts := getCloudProviderNTPHosts(context.TODO())
// Default to our domains on pool.ntp.org if no cloud provider detected
if defaultHosts == nil {
log.Debugf("No cloud provider detected, using default ntp pool: [ %s ]", strings.Join(defaultDatadogPool, ", "))
defaultHosts = defaultDatadogPool
}
if err := yaml.Unmarshal(data, &instance); err != nil {
return err
}
if err := yaml.Unmarshal(initData, &initConf); err != nil {
return err
}
c.instance = instance
var localNtpServers []string
var err error
if c.instance.UseLocalDefinedServers {
localNtpServers, err = getLocalServers()
if err != nil {
return err
}
log.Debugf("Detected local defined servers: [ %s ]", strings.Join(defaultDatadogPool, ", "))
}
if len(localNtpServers) > 0 {
c.instance.Hosts = localNtpServers
} else if c.instance.Host != "" {
hosts := []string{c.instance.Host}
// If config contains both host and hosts
for _, h := range c.instance.Hosts {
if h != c.instance.Host {
hosts = append(hosts, h)
}
}
c.instance.Hosts = hosts
}
if c.instance.Hosts == nil {
c.instance.Hosts = defaultHosts
}
log.Infof("Using NTP servers: [ %s ]", strings.Join(c.instance.Hosts, ", "))
if c.instance.Port == 0 {
c.instance.Port = defaultPort
}
if c.instance.Version == 0 {
c.instance.Version = defaultVersion
}
if c.instance.Timeout == 0 {
c.instance.Timeout = defaultTimeout
}
if c.instance.OffsetThreshold == 0 {
c.instance.OffsetThreshold = defaultOffsetThreshold
}
c.initConf = initConf
return nil
}
// Configure configure the data from the yaml
func (c *NTPCheck) Configure(senderManager sender.SenderManager, integrationConfigDigest uint64, data integration.Data, initConfig integration.Data, source string) error {
cfg := new(ntpConfig)
err := cfg.parse(data, initConfig, getLocalDefinedNTPServers)
if err != nil {
log.Errorf("Error parsing configuration file: %s", err)
return err
}
c.BuildID(integrationConfigDigest, data, initConfig)
c.cfg = cfg
err = c.CommonConfigure(senderManager, initConfig, data, source)
if err != nil {
return err
}
return nil
}
// Run runs the check
func (c *NTPCheck) Run() error {
sender, err := c.GetSender()
if err != nil {
return err
}
var serviceCheckStatus servicecheck.ServiceCheckStatus
serviceCheckMessage := ""
offsetThreshold := c.cfg.instance.OffsetThreshold
clockOffset, err := c.queryOffset()
if err != nil {
log.Error(err)
sender.ServiceCheck("ntp.in_sync", servicecheck.ServiceCheckUnknown, "", nil, serviceCheckMessage)
c.lastCollection = time.Now()
sender.Commit()
return err
}
if int(math.Abs(clockOffset)) > offsetThreshold {
serviceCheckStatus = servicecheck.ServiceCheckCritical
serviceCheckMessage = fmt.Sprintf("Offset %v is higher than offset threshold (%v secs)", clockOffset, offsetThreshold)
} else {
serviceCheckStatus = servicecheck.ServiceCheckOK
}
sender.Gauge("ntp.offset", clockOffset, "", nil)
ntpExpVar.Set(clockOffset)
tlmNtpOffset.Set(clockOffset)
sender.ServiceCheck("ntp.in_sync", serviceCheckStatus, "", nil, serviceCheckMessage)
c.lastCollection = time.Now()
sender.Commit()
return nil
}
func (c *NTPCheck) queryOffset() (float64, error) {
offsets := []float64{}
for _, host := range c.cfg.instance.Hosts {
response, err := ntpQuery(host, ntp.QueryOptions{Version: c.cfg.instance.Version, Port: c.cfg.instance.Port, Timeout: time.Duration(c.cfg.instance.Timeout) * time.Second})
if err != nil {
log.Debugf("There was an error querying the ntp host %s: %s", host, err)
continue
}
err = response.Validate()
if err != nil {
log.Infof("The ntp response is not valid for host %s: %s", host, err)
continue
}
offsets = append(offsets, response.ClockOffset.Seconds())
}
if len(offsets) == 0 {
return .0, fmt.Errorf("failed to get clock offset from any ntp host: [ %s ]", strings.Join(c.cfg.instance.Hosts, ", "))
}
var median float64
sort.Float64s(offsets)
length := len(offsets)
if length%2 == 0 {
median = (offsets[length/2-1] + offsets[length/2]) / 2.0
} else {
median = offsets[length/2]
}
return median, nil
}
// Factory creates a new check factory
func Factory() optional.Option[func() check.Check] {
return optional.NewOption(newCheck)
}
func newCheck() check.Check {
return &NTPCheck{
CheckBase: core.NewCheckBaseWithInterval(CheckName, time.Duration(defaultMinCollectionInterval)*time.Second),
}
}