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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
use std::{path::PathBuf, process::ExitCode};

use crate::{
    daemon::{Config, ObservableState, config::CliArg, tracing::LogLevel},
    force_sync,
};
use tokio::runtime::Builder;
use tracing_subscriber::util::SubscriberInitExt;

const USAGE_MSG: &str = "\
usage: ntp-ctl validate [-c PATH]
       ntp-ctl status [-f FORMAT] [-c PATH]
       ntp-ctl force-sync [-c PATH]
       ntp-ctl -h | ntp-ctl -v";

const DESCRIPTOR: &str = "ntp-ctl - ntp-daemon monitoring";

const HELP_MSG: &str = "Options:
  -f, --format=FORMAT                  which format to use for printing statistics [plain, prometheus]
  -c, --config=CONFIG                  which configuration file to read the socket paths from
  -h, --help                           display this help text
  -v, --version                        display version information";

pub fn long_help_message() -> String {
    format!("{DESCRIPTOR}\n\n{USAGE_MSG}\n\n{HELP_MSG}")
}

#[derive(Debug, Default, PartialEq, Eq)]
enum Format {
    #[default]
    Plain,
    Prometheus,
}

#[derive(Debug, Default, PartialEq, Eq)]
pub enum NtpCtlAction {
    #[default]
    Help,
    Version,
    Validate,
    Status,
    ForceSync,
}

#[derive(Debug, Default)]
pub(crate) struct NtpCtlOptions {
    config: Option<PathBuf>,
    format: Format,
    help: bool,
    version: bool,
    validate: bool,
    status: bool,
    force_sync: bool,
    action: NtpCtlAction,
}

impl NtpCtlOptions {
    const TAKES_ARGUMENT: &'static [&'static str] = &["--config", "--format"];
    const TAKES_ARGUMENT_SHORT: &'static [char] = &['c', 'f'];

    /// parse an iterator over command line arguments
    pub fn try_parse_from<I, T>(iter: I) -> Result<Self, String>
    where
        I: IntoIterator<Item = T>,
        T: AsRef<str> + Clone,
    {
        let mut options = NtpCtlOptions::default();

        let it = iter.into_iter().map(|x| x.as_ref().to_string());

        let arg_iter =
            CliArg::normalize_arguments(Self::TAKES_ARGUMENT, Self::TAKES_ARGUMENT_SHORT, it)?
                .into_iter()
                .peekable();

        for arg in arg_iter {
            match arg {
                CliArg::Flag(flag) => match flag.as_str() {
                    "-h" | "--help" => {
                        options.help = true;
                    }
                    "-v" | "--version" => {
                        options.version = true;
                    }
                    option => {
                        Err(format!("invalid option provided: {option}"))?;
                    }
                },
                CliArg::Argument(option, value) => match option.as_str() {
                    "-c" | "--config" => {
                        options.config = Some(PathBuf::from(value));
                    }
                    "-f" | "--format" => match value.as_str() {
                        "plain" => options.format = Format::Plain,
                        "prometheus" => options.format = Format::Prometheus,
                        _ => Err(format!("invalid format option provided: {value}"))?,
                    },
                    option => {
                        Err(format!("invalid option provided: {option}"))?;
                    }
                },
                CliArg::Rest(rest) => {
                    if rest.len() > 1 {
                        eprintln!("Warning: Too many commands provided.");
                    }
                    for command in rest {
                        match command.as_str() {
                            "validate" => {
                                options.validate = true;
                            }
                            "status" => {
                                options.status = true;
                            }
                            "force-sync" => {
                                options.force_sync = true;
                            }
                            unknown => {
                                eprintln!("Warning: Unknown command {unknown}");
                            }
                        }
                    }
                }
            }
        }

        options.resolve_action();
        // nothing to validate at the moment

        Ok(options)
    }

    /// from the arguments resolve which action should be performed
    fn resolve_action(&mut self) {
        if self.help {
            self.action = NtpCtlAction::Help;
        } else if self.version {
            self.action = NtpCtlAction::Version;
        } else if self.validate {
            self.action = NtpCtlAction::Validate;
        } else if self.status {
            self.action = NtpCtlAction::Status;
        } else if self.force_sync {
            self.action = NtpCtlAction::ForceSync;
        } else {
            self.action = NtpCtlAction::Help;
        }
    }
}

fn validate(config: Option<PathBuf>) -> std::io::Result<ExitCode> {
    // Late completion not needed, so ignore result.
    crate::daemon::tracing::tracing_init(LogLevel::Info, None, true)
        .0
        .init();
    match Config::from_args(config, vec![], vec![]) {
        Ok(config) => {
            if config.check() {
                eprintln!("Config looks good");
                Ok(ExitCode::SUCCESS)
            } else {
                Ok(ExitCode::FAILURE)
            }
        }
        Err(e) => {
            eprintln!("Error: Could not load configuration: {e}");
            Ok(ExitCode::FAILURE)
        }
    }
}

const VERSION: &str = env!("CARGO_PKG_VERSION");

pub fn main() -> std::io::Result<ExitCode> {
    let options = match NtpCtlOptions::try_parse_from(std::env::args()) {
        Ok(options) => options,
        Err(msg) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, msg)),
    };

    match options.action {
        NtpCtlAction::Help => {
            println!("{}", long_help_message());
            Ok(ExitCode::SUCCESS)
        }
        NtpCtlAction::Version => {
            eprintln!("ntp-ctl {VERSION}");
            Ok(ExitCode::SUCCESS)
        }
        NtpCtlAction::Validate => validate(options.config),
        NtpCtlAction::ForceSync => force_sync::force_sync(options.config),
        NtpCtlAction::Status => {
            let config = Config::from_args(options.config, vec![], vec![]);

            if let Err(ref e) = config {
                println!("Warning: Unable to load configuration file: {e}");
            }

            let config = config.unwrap_or_default();

            let observation = config
                .observability
                .observation_path
                .unwrap_or_else(|| PathBuf::from("/var/run/ntpd-rs/observe"));

            Builder::new_current_thread()
                .enable_all()
                .build()?
                .block_on(async {
                    match options.format {
                        Format::Plain => print_state(Format::Plain, observation).await,
                        Format::Prometheus => print_state(Format::Prometheus, observation).await,
                    }
                })
        }
    }
}

async fn print_state(print: Format, observe_socket: PathBuf) -> Result<ExitCode, std::io::Error> {
    let mut stream = match tokio::net::UnixStream::connect(&observe_socket).await {
        Ok(stream) => stream,
        Err(e) => {
            eprintln!("Could not open socket at {}: {e}", observe_socket.display(),);
            return Ok(ExitCode::FAILURE);
        }
    };

    let mut msg = Vec::with_capacity(16 * 1024);
    let mut output =
        match crate::daemon::sockets::read_json::<ObservableState>(&mut stream, &mut msg).await {
            Ok(output) => output,
            Err(e) => {
                eprintln!("Failed to read state from observation socket: {e}");

                return Ok(ExitCode::FAILURE);
            }
        };

    match print {
        Format::Plain => {
            // Sort sources by address and then id (to deal with pools), servers just by address
            output.sources.sort_by_key(|s| (s.name.clone(), s.id));
            output.servers.sort_by_key(|s| s.address);

            println!("Synchronization status:");
            println!(
                "Dispersion: {:.6}s, Delay: {:.6}s",
                output
                    .system
                    .time_snapshot
                    .root_dispersion(output.program.now)
                    .to_seconds(),
                output.system.time_snapshot.root_delay.to_seconds()
            );
            println!("Stratum: {}", output.system.stratum);
            println!();
            println!("Sources:");
            for source in &output.sources {
                println!(
                    "{}/{}{} ({}): {:+.6}±{:.6}(±{:.6})s",
                    source.name,
                    source.address,
                    source.nts_cookies.map_or("", |_| " [NTS]"),
                    source.id,
                    source.timedata.offset.to_seconds(),
                    source.timedata.uncertainty.to_seconds(),
                    source.timedata.delay.to_seconds(),
                );
                println!(
                    "    poll interval: {:.0}s, missing polls: {}",
                    source.poll_interval.as_duration().to_seconds(),
                    source.unanswered_polls,
                );
                println!(
                    "    root dispersion: {:.6}s, root delay:{:.6}s",
                    source.timedata.remote_uncertainty.to_seconds(),
                    source.timedata.remote_delay.to_seconds()
                );
                if let Some(nts_cookies) = source.nts_cookies {
                    println!(
                        "    NTS cookies: {}/{} available",
                        nts_cookies,
                        ntp_proto::MAX_COOKIES
                    );
                }
            }
            println!();
            println!("Servers:");
            for server in &output.servers {
                println!(
                    "{}: received {}, accepted {}, errors {}",
                    server.address,
                    server.stats.received_packets.get(),
                    server.stats.accepted_packets.get(),
                    server.stats.response_send_errors.get()
                );
                println!(
                    "    denied {}, nts nak {}, rate limited {}, ignored {}",
                    server.stats.denied_packets.get(),
                    server.stats.nts_nak_packets.get(),
                    server.stats.rate_limited_packets.get(),
                    server.stats.ignored_packets.get()
                );
            }
        }
        Format::Prometheus => {
            let mut buf = String::new();
            if let Err(e) = crate::metrics::format_state(&mut buf, &output) {
                eprintln!("Failed to encode prometheus data: {e}");

                return Ok(ExitCode::FAILURE);
            }

            println!("{buf}");
        }
    }

    Ok(ExitCode::SUCCESS)
}

#[cfg(test)]
mod tests {
    use std::os::unix::prelude::PermissionsExt;
    use std::path::Path;

    use ntp_proto::SystemSnapshot;

    use crate::{
        daemon::{
            config::ObservabilityConfig,
            observer::ProgramData,
            sockets::{create_unix_socket_with_permissions, write_json},
        },
        test::alloc_port,
    };

    use super::*;

    async fn write_socket_helper<T: serde::Serialize>(
        command: Format,
        value: T,
    ) -> std::io::Result<Result<ExitCode, std::io::Error>> {
        let config: ObservabilityConfig = ObservabilityConfig::default();

        // be careful with copying: tests run concurrently and should use a unique socket name!
        let path = std::env::temp_dir().join(format!("ntp-test-stream-{}", alloc_port()));
        if path.exists() {
            std::fs::remove_file(&path).unwrap();
        }

        let permissions: std::fs::Permissions =
            PermissionsExt::from_mode(config.observation_permissions);

        let sources_listener = create_unix_socket_with_permissions(&path, permissions)?;

        let fut = super::print_state(command, path);
        let handle = tokio::spawn(fut);

        let (mut stream, _addr) = sources_listener.accept().await?;
        write_json(&mut stream, &value).await?;

        let result = handle.await.unwrap();

        Ok(result)
    }

    #[tokio::test]
    async fn test_control_socket_source() -> std::io::Result<()> {
        let value = ObservableState {
            program: ProgramData::default(),
            system: SystemSnapshot::default(),
            sources: vec![],
            servers: vec![],
        };
        let result = write_socket_helper(Format::Plain, value).await?;

        assert_eq!(
            format!("{:?}", result.unwrap()),
            format!("{:?}", ExitCode::SUCCESS)
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_control_socket_prometheus() -> std::io::Result<()> {
        let value = ObservableState {
            program: ProgramData::default(),
            system: SystemSnapshot::default(),
            sources: vec![],
            servers: vec![],
        };
        let result = write_socket_helper(Format::Prometheus, value).await?;

        assert_eq!(
            format!("{:?}", result.unwrap()),
            format!("{:?}", ExitCode::SUCCESS)
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_control_socket_source_invalid_input() -> std::io::Result<()> {
        let value = 42u32;
        let result = write_socket_helper(Format::Plain, value).await?;

        assert_eq!(
            format!("{:?}", result.unwrap()),
            format!("{:?}", ExitCode::FAILURE)
        );

        Ok(())
    }

    const BINARY: &str = "/usr/bin/ntp-ctl";

    #[test]
    fn cli_config() {
        let config_str = "/foo/bar/ntp.toml";
        let config = Path::new(config_str);
        let arguments = &[BINARY, "-c", config_str];

        let options = NtpCtlOptions::try_parse_from(arguments).unwrap();
        assert_eq!(options.config.unwrap().as_path(), config);
    }

    #[test]
    fn cli_format() {
        let arguments = &[BINARY, "-f", "plain"];
        let options = NtpCtlOptions::try_parse_from(arguments).unwrap();
        assert_eq!(options.format, Format::Plain);

        let arguments = &[BINARY, "-f", "prometheus"];
        let options = NtpCtlOptions::try_parse_from(arguments).unwrap();
        assert_eq!(options.format, Format::Prometheus);

        let arguments = &[BINARY, "-f", "yaml"];
        let err = NtpCtlOptions::try_parse_from(arguments).unwrap_err();
        assert_eq!(err, "invalid format option provided: yaml");
    }
}