-
-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathmod.rs
More file actions
211 lines (177 loc) · 6.77 KB
/
Copy pathmod.rs
File metadata and controls
211 lines (177 loc) · 6.77 KB
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
mod clock;
pub mod config;
#[cfg(target_os = "linux")]
mod csptp_server;
#[cfg(target_os = "linux")]
mod csptp_source;
mod dns;
pub mod keyexchange;
mod local_ip_provider;
mod ntp_source;
pub mod nts_key_provider;
pub mod observer;
#[cfg(feature = "pps")]
mod pps_source;
mod server;
mod sock_source;
pub mod sockets;
pub mod spawn;
mod system;
pub mod tracing;
mod util;
use std::{error::Error, io::IsTerminal, path::Path};
use ::tracing::info;
pub use config::Config;
use self::clock::{NtpClockWrapper, SoftClock};
use ntp_proto::{KalmanClockController, TimeSyncControllerWrapper};
pub use observer::ObservableState;
pub use system::spawn;
use tokio::runtime::Builder;
use tracing_subscriber::util::SubscriberInitExt;
use config::NtpDaemonOptions;
use crate::daemon::tracing::LogReloadTaskStarter;
use crate::notify::notify_ready;
use self::tracing::LogLevel;
const VERSION: &str = env!("CARGO_PKG_VERSION");
pub fn main() -> Result<(), Box<dyn Error>> {
let options = NtpDaemonOptions::try_parse_from(std::env::args())?;
#[cfg(feature = "openssl")]
rustls_openssl::default_provider()
.install_default()
.expect("Failed to use rustls_openssl");
match options.action {
config::NtpDaemonAction::Help => {
println!("{}", config::long_help_message());
}
config::NtpDaemonAction::Version => {
eprintln!("ntp-daemon {VERSION}");
}
config::NtpDaemonAction::Run => run(&options)?,
}
Ok(())
}
#[derive(Debug, Copy, Clone)]
pub(crate) enum Application {
Deamon,
MetricsExporter,
#[expect(unused)]
Ctl,
}
// initializes the logger so that logs during config parsing are reported. Then it overrides the
// log level based on the config if required.
pub(crate) fn initialize_logging_parse_config(
initial_log_level: Option<LogLevel>,
config_path: Option<&Path>,
app: Application,
) -> (Config, Option<LogReloadTaskStarter>) {
let mut log_level = initial_log_level.unwrap_or_default();
let (config_tracing, _) = crate::daemon::tracing::tracing_init(log_level, None, true);
let (config, tracing_inst, task_starter) =
::tracing::subscriber::with_default(config_tracing, || {
let config = match Config::from_args(config_path.as_ref(), vec![], vec![]) {
Ok(c) => c,
Err(e) => {
// print to stderr because tracing is not yet setup
eprintln!("There was an error loading the config: {e}");
std::process::exit(exitcode::CONFIG);
}
};
if let Some(config_log_level) = config.observability.log_level
&& initial_log_level.is_none()
{
log_level = config_log_level;
}
let log_path = match app {
Application::Deamon => config.observability.log_path.clone(),
Application::MetricsExporter => {
config.observability.log_path_metrics_exporter.clone()
}
Application::Ctl => None,
};
let ansi_colors = config
.observability
.ansi_colors
.unwrap_or_else(|| log_path.is_none() && std::io::stdout().is_terminal());
// set a default global subscriber from now on
let (tracing_inst, task_starter) =
self::tracing::tracing_init(log_level, log_path, ansi_colors);
(config, tracing_inst, task_starter)
});
tracing_inst.init();
(config, task_starter)
}
fn run(options: &NtpDaemonOptions) -> Result<(), Box<dyn Error>> {
let (config, task_starter) = initialize_logging_parse_config(
options.log_level,
options.config.as_deref(),
Application::Deamon,
);
let runtime = if config.servers.is_empty() && config.nts_ke.is_empty() {
Builder::new_current_thread().enable_all().build()?
} else {
Builder::new_multi_thread().enable_all().build()?
};
runtime.block_on(async move {
if let Some(task_starter) = task_starter {
task_starter.start();
}
// give the user a warning that we use the command line option
if config.observability.log_level.is_some() && options.log_level.is_some() {
info!("Log level override from command line arguments is active");
}
// Warn/error if the config is unreasonable. We do this after finishing
// tracing setup to ensure logging is fully configured.
config.check();
// we always generate the keyset (even if NTS is not used)
let keyset = nts_key_provider::spawn(config.keyset).await;
#[cfg(feature = "hardware-timestamping")]
let clock_config = config.clock;
#[cfg(not(feature = "hardware-timestamping"))]
let clock_config = config::ClockConfig::default();
::tracing::debug!("Configuration loaded, spawning daemon jobs");
let clock = SoftClock::new(clock_config.clock, config.synchronization.update_system_clock);
let (main_loop_handle, channels) =
spawn::<SoftClock<NtpClockWrapper>, TimeSyncControllerWrapper<KalmanClockController<SoftClock<NtpClockWrapper>>>>(
config.synchronization.synchronization_base,
config.synchronization.algorithm,
config.source_defaults,
clock.clone(),
clock_config.interface,
clock_config.timestamp_mode,
&config.sources,
&config.servers,
#[cfg(target_os = "linux")]
&config.csptp_servers,
keyset.clone(),
#[cfg(target_os = "linux")]
config.csptp,
)
.await?;
for nts_ke_config in config.nts_ke {
let _join_handle = keyexchange::spawn(nts_ke_config, keyset.clone());
}
observer::spawn(
&config.observability,
channels.source_snapshots,
channels.server_data_receiver,
channels.system_snapshot_receiver,
clock,
config.synchronization.update_system_clock,
);
let _ = notify_ready().await;
Ok(main_loop_handle.await??)
})
}
pub(crate) mod exitcode {
/// An internal software error has been detected. This
/// should be limited to non-operating system related
/// errors as possible.
pub const SOFTWARE: i32 = 70;
/// You did not have sufficient permission to perform
/// the operation. This is not intended for file system
/// problems, which should use `NOINPUT` or `CANTCREAT`,
/// but rather for higher level permissions.
pub const NOPERM: i32 = 77;
/// Something was found in an unconfigured or misconfigured state.
pub const CONFIG: i32 = 78;
}