ntpd 1.7.2

Full-featured implementation of NTP with NTS support
Documentation
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
pub mod exporter;

use ntp_proto::{NtpDuration, PollIntervalLimits};

use crate::daemon::ObservableState;

struct Measurement<T> {
    labels: Vec<(&'static str, String)>,
    value: T,
}

impl<T> Measurement<T> {
    fn simple(value: T) -> Vec<Measurement<T>> {
        vec![Measurement {
            labels: vec![],
            value,
        }]
    }
}

#[derive(PartialEq, Eq, Clone, Copy)]
enum Unit {
    Seconds,
}

impl Unit {
    fn as_str(&self) -> &str {
        "seconds"
    }
}

enum MetricType {
    Gauge,
    Counter,
}

impl MetricType {
    fn as_str(&self) -> &str {
        match self {
            MetricType::Gauge => "gauge",
            MetricType::Counter => "counter",
        }
    }
}

fn format_metric<T: std::fmt::Display>(
    w: &mut impl std::fmt::Write,
    name: &str,
    help: &str,
    metric_type: MetricType,
    unit: Option<Unit>,
    measurements: Vec<Measurement<T>>,
) -> std::fmt::Result {
    let name = if let Some(unit) = unit {
        format!("{}_{}", name, unit.as_str())
    } else {
        name.to_owned()
    };

    // write help text
    writeln!(w, "# HELP {name} {help}.")?;

    // write type
    writeln!(w, "# TYPE {name} {}", metric_type.as_str())?;

    // write unit
    if let Some(unit) = unit {
        writeln!(w, "# UNIT {name} {}", unit.as_str())?;
    }

    // write all the measurements
    for measurement in measurements {
        w.write_str(&name)?;
        if !measurement.labels.is_empty() {
            w.write_str("{")?;

            for (offset, (label, value)) in measurement.labels.iter().enumerate() {
                let value = value
                    .replace('\\', "\\\\")
                    .replace('"', "\\\"")
                    .replace('\n', "\\n");
                write!(w, "{label}=\"{value}\"")?;
                if offset < measurement.labels.len() - 1 {
                    w.write_str(",")?;
                }
            }
            w.write_str("}")?;
        }
        w.write_str(" ")?;
        write!(w, "{}", measurement.value)?;
        w.write_str("\n")?;
    }

    Ok(())
}

macro_rules! collect_sources {
    ($from: expr, |$ident: ident| $value: expr $(,)?) => {{
        let mut data = vec![];
        for $ident in &$from.sources {
            let labels = vec![
                ("name", $ident.name.clone()),
                ("address", $ident.address.clone()),
                ("id", format!("{}", $ident.id)),
            ];
            let value = $value;
            data.push(Measurement { labels, value });
        }
        data
    }};
}

macro_rules! collect_some_sources {
    ($from: expr, |$ident: ident| $value: expr $(,)?) => {{
        let mut data = vec![];
        for $ident in &$from.sources {
            if let Some(value) = $value {
                let labels = vec![
                    ("name", $ident.name.clone()),
                    ("address", $ident.address.clone()),
                    ("id", format!("{}", $ident.id)),
                ];
                data.push(Measurement { labels, value });
            }
        }
        data
    }};
}

macro_rules! collect_servers {
    ($from: expr, |$ident: ident| $value: expr $(,)?) => {{
        let mut data = vec![];
        for $ident in &$from.servers {
            let labels = vec![("listen_address", format!("{}", $ident.address))];
            let value = $value;
            data.push(Measurement { labels, value })
        }
        data
    }};
}

// Allow this function to be oversized as it is otherwise straightforward
// and has no reasonable way to be split.
#[expect(clippy::too_many_lines)]
pub fn format_state(w: &mut impl std::fmt::Write, state: &ObservableState) -> std::fmt::Result {
    format_metric(
        w,
        "ntp_uptime",
        "Time that the ntp daemon is running",
        MetricType::Gauge,
        Some(Unit::Seconds),
        vec![Measurement {
            labels: vec![
                ("version", state.program.version.clone()),
                ("build_commit", state.program.build_commit.clone()),
                ("build_commit_date", state.program.build_commit_date.clone()),
            ],
            value: state.program.uptime_seconds,
        }],
    )?;

    format_metric(
        w,
        "ntp_system_poll_interval",
        "[DEPRECATED] Time between polls of the system",
        MetricType::Gauge,
        Some(Unit::Seconds),
        Measurement::simple(
            state
                .sources
                .iter()
                .map(|s| s.poll_interval)
                .min()
                .unwrap_or(PollIntervalLimits::default().min)
                .as_duration()
                .to_seconds(),
        ),
    )?;

    format_metric(
        w,
        "ntp_system_accumulated_steps",
        "Accumulated amount of seconds that the system needed to jump the time",
        MetricType::Gauge,
        Some(Unit::Seconds),
        Measurement::simple(state.system.time_snapshot.accumulated_steps.to_seconds()),
    )?;

    format_metric(
        w,
        "ntp_system_accumulated_steps_threshold",
        "Threshold for the accumulated step amount at which the NTP daemon will exit (or -1 if no threshold was set)",
        MetricType::Gauge,
        Some(Unit::Seconds),
        Measurement::simple(
            state
                .system
                .accumulated_steps_threshold
                .map_or(-1.0, NtpDuration::to_seconds),
        ),
    )?;

    format_metric(
        w,
        "ntp_system_leap_indicator",
        "Indicates that a leap second will take place",
        MetricType::Gauge,
        None,
        Measurement::simple(state.system.time_snapshot.leap_indicator as i64),
    )?;

    format_metric(
        w,
        "ntp_system_root_delay",
        "Distance to the closest root time source",
        MetricType::Gauge,
        Some(Unit::Seconds),
        Measurement::simple(state.system.time_snapshot.root_delay.to_seconds()),
    )?;

    format_metric(
        w,
        "ntp_system_root_dispersion",
        "Estimate of how precise our time is",
        MetricType::Gauge,
        Some(Unit::Seconds),
        Measurement::simple(
            state
                .system
                .time_snapshot
                .root_dispersion(state.program.now)
                .to_seconds(),
        ),
    )?;

    format_metric(
        w,
        "ntp_system_stratum",
        "Stratum of our clock",
        MetricType::Gauge,
        None,
        Measurement::simple(state.system.stratum),
    )?;

    format_metric(
        w,
        "ntp_source_poll_interval",
        "Time between polls of the source",
        MetricType::Gauge,
        Some(Unit::Seconds),
        collect_sources!(state, |p| p.poll_interval.as_duration().to_seconds()),
    )?;

    format_metric(
        w,
        "ntp_source_unanswered_polls",
        "Number of polls since the last successful poll with a maximum of eight",
        MetricType::Gauge,
        None,
        collect_sources!(state, |p| p.unanswered_polls),
    )?;

    format_metric(
        w,
        "ntp_source_nts_cookies_available",
        "Number of unused cookies available for nts-enabled ntp exchanges",
        MetricType::Gauge,
        None,
        collect_some_sources!(state, |p| p.nts_cookies),
    )?;

    format_metric(
        w,
        "ntp_source_offset",
        "Offset between the upstream source and system time",
        MetricType::Gauge,
        Some(Unit::Seconds),
        collect_sources!(state, |p| p.timedata.offset.to_seconds()),
    )?;

    format_metric(
        w,
        "ntp_source_delay",
        "Current round-trip delay to the upstream source",
        MetricType::Gauge,
        Some(Unit::Seconds),
        collect_sources!(state, |p| p.timedata.delay.to_seconds()),
    )?;

    format_metric(
        w,
        "ntp_source_uncertainty",
        "Estimated error of the source clock",
        MetricType::Gauge,
        Some(Unit::Seconds),
        collect_sources!(state, |p| p.timedata.uncertainty.to_seconds()),
    )?;

    format_metric(
        w,
        "ntp_source_root_delay",
        "Root delay reported by the time source",
        MetricType::Gauge,
        Some(Unit::Seconds),
        collect_sources!(state, |p| p.timedata.remote_delay.to_seconds()),
    )?;

    format_metric(
        w,
        "ntp_source_root_dispersion",
        "Uncertainty reported by the time source",
        MetricType::Gauge,
        Some(Unit::Seconds),
        collect_sources!(state, |p| p.timedata.remote_uncertainty.to_seconds()),
    )?;

    format_metric(
        w,
        "ntp_server_received_packets_total",
        "Number of incoming packets",
        MetricType::Counter,
        None,
        collect_servers!(state, |s| s.stats.received_packets.get()),
    )?;

    format_metric(
        w,
        "ntp_server_accepted_packets_total",
        "Number of packets accepted",
        MetricType::Counter,
        None,
        collect_servers!(state, |s| s.stats.accepted_packets.get()),
    )?;

    format_metric(
        w,
        "ntp_server_denied_packets_total",
        "Number of denied packets",
        MetricType::Counter,
        None,
        collect_servers!(state, |s| s.stats.denied_packets.get()),
    )?;

    format_metric(
        w,
        "ntp_server_ignored_packets_total",
        "Number of packets ignored",
        MetricType::Counter,
        None,
        collect_servers!(state, |s| s.stats.ignored_packets.get()),
    )?;

    format_metric(
        w,
        "ntp_server_rate_limited_packets_total",
        "Number of rate limited packets",
        MetricType::Counter,
        None,
        collect_servers!(state, |s| s.stats.rate_limited_packets.get()),
    )?;

    format_metric(
        w,
        "ntp_server_response_send_errors_total",
        "Number of packets where there was an error responding",
        MetricType::Counter,
        None,
        collect_servers!(state, |s| s.stats.response_send_errors.get()),
    )?;

    format_metric(
        w,
        "ntp_server_nts_received_packets_total",
        "Number of incoming NTS packets",
        MetricType::Counter,
        None,
        collect_servers!(state, |s| s.stats.nts_received_packets.get()),
    )?;

    format_metric(
        w,
        "ntp_server_nts_accepted_packets_total",
        "Number of NTS packets accepted",
        MetricType::Counter,
        None,
        collect_servers!(state, |s| s.stats.nts_accepted_packets.get()),
    )?;

    format_metric(
        w,
        "ntp_server_nts_denied_packets_total",
        "Number of denied NTS packets",
        MetricType::Counter,
        None,
        collect_servers!(state, |s| s.stats.nts_denied_packets.get()),
    )?;

    format_metric(
        w,
        "ntp_server_nts_rate_limited_packets_total",
        "Number of rate limited NTS packets",
        MetricType::Counter,
        None,
        collect_servers!(state, |s| s.stats.nts_rate_limited_packets.get()),
    )?;

    format_metric(
        w,
        "ntp_server_nts_nak_packets_total",
        "Number of NTS nak responses to packets",
        MetricType::Counter,
        None,
        collect_servers!(state, |s| s.stats.nts_nak_packets.get()),
    )?;

    w.write_str("# EOF\n")?;
    Ok(())
}