-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathmain.rs
334 lines (289 loc) · 10.1 KB
/
main.rs
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use std::fmt;
use std::net::{IpAddr, Ipv6Addr, SocketAddr};
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use propolis::usdt::register_probes;
use propolis_server::{
config,
server::{self, MetricsEndpointConfig},
vnc,
};
use anyhow::{anyhow, Context};
use clap::Parser;
use dropshot::{ConfigDropshot, HandlerTaskMode, HttpServerStarter};
use slog::{info, Logger};
/// Threads to spawn for tokio runtime handling the API (dropshot, etc)
const API_RT_THREADS: usize = 4;
/// Configuration for metric registration.
#[derive(Clone, Debug, PartialEq)]
enum MetricRegistration {
Disable,
Dns,
WithAddr(SocketAddr),
}
impl fmt::Display for MetricRegistration {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MetricRegistration::Disable => "disable".fmt(f),
MetricRegistration::Dns => "dns".fmt(f),
MetricRegistration::WithAddr(addr) => addr.fmt(f),
}
}
}
impl FromStr for MetricRegistration {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.eq_ignore_ascii_case("disable") {
Ok(Self::Disable)
} else if s.eq_ignore_ascii_case("dns") {
Ok(Self::Dns)
} else {
let Ok(addr) = s.parse() else {
anyhow::bail!(
"Metric registration must be 'disable', \
'dns', or an explicit socket address \
written as `IP:port`",
);
};
Ok(Self::WithAddr(addr))
}
}
}
fn parse_log_level(s: &str) -> anyhow::Result<slog::Level> {
s.parse().map_err(|_| anyhow::anyhow!("Invalid log level"))
}
#[derive(Debug, Parser)]
#[clap(about, version)]
/// An HTTP server providing access to Propolis
enum Args {
/// Generates the OpenAPI specification.
OpenApi,
/// Runs the Propolis server.
Run {
#[clap(action)]
bootrom_path: PathBuf,
#[clap(name = "PROPOLIS_IP:PORT", action)]
propolis_addr: SocketAddr,
#[clap(long, action)]
bootrom_version: Option<String>,
/// Method for registering as an Oximeter metric producer.
///
/// The following values are supported:
///
/// disable - Do not register or attempt to produce metrics.
///
/// dns - Register at an address inferred from Oxide internal DNS.
/// This is only available if the Propolis is listening on a
/// non-localhost IPv6 address.
///
/// IP:port - Register with the explicitly-provided socket address.
#[clap(long, default_value_t = MetricRegistration::Disable)]
metric_addr: MetricRegistration,
/// IP:Port for raw TCP access to VNC console
#[clap(name = "VNC_IP:PORT", action)]
vnc_addr: Option<SocketAddr>,
/// Logging level for the server
#[clap(long, default_value_t = slog::Level::Info, value_parser = parse_log_level)]
log_level: slog::Level,
},
}
pub fn run_openapi() -> Result<(), String> {
server::api()
.openapi("Oxide Propolis Server API", "0.0.1")
.description(
"API for interacting with the Propolis hypervisor frontend.",
)
.contact_url("https://oxide.computer")
.contact_email("api@oxide.computer")
.write(&mut std::io::stdout())
.map_err(|e| e.to_string())
}
fn run_server(
bootrom_path: PathBuf,
bootrom_version: Option<String>,
config_dropshot: dropshot::ConfigDropshot,
config_metrics: Option<MetricsEndpointConfig>,
vnc_addr: Option<SocketAddr>,
log: slog::Logger,
) -> anyhow::Result<()> {
use propolis::api_version;
// Check that devices conform to expected API version
if let Err(e) = api_version::check() {
if let api_version::Error::Io(ioe) = &e {
if ioe.kind() == std::io::ErrorKind::NotFound {
slog::error!(log, "Failed to open /dev/vmmctl");
}
}
Err(e).context("API version checks")?;
}
// If this is a development image being run outside of an Omicron zone,
// enable the display (in logs, panic messages, and the like) of diagnostic
// data that may have originated in the guest.
#[cfg(not(feature = "omicron-build"))]
propolis::common::DISPLAY_GUEST_DATA
.store(true, std::sync::atomic::Ordering::SeqCst);
let use_reservoir = config::reservoir_decide(&log);
let context = server::DropshotEndpointContext::new(
bootrom_path,
bootrom_version,
use_reservoir,
log.new(slog::o!()),
config_metrics,
);
// Spawn the runtime for handling API processing
// If/when a VM instance is created, a separate runtime for handling device
// emulation and other VM-related work will be spawned.
let api_runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(API_RT_THREADS)
.enable_all()
.thread_name("tokio-rt-api")
.build()?;
let _guard = api_runtime.enter();
// Start TCP listener for VNC, if requested
let tcp_vnc = match vnc_addr {
Some(addr) => Some(api_runtime.block_on(async {
vnc::TcpSock::new(context.vnc_server.clone(), addr, log.clone())
.await
})?),
None => None,
};
info!(log, "Starting server...");
let server = HttpServerStarter::new(
&config_dropshot,
server::api(),
Arc::new(context),
&log,
)
.map_err(|error| anyhow!("Failed to start server: {}", error))?
.start();
let result = api_runtime.block_on(server);
// Clean up any VNC TCP socket
if let Some(vnc) = tcp_vnc {
api_runtime.block_on(async { vnc.halt().await });
}
result.map_err(|e| anyhow!("Server exited with an error: {}", e))
}
fn build_logger(level: slog::Level) -> slog::Logger {
use slog::Drain;
let main_drain = if atty::is(atty::Stream::Stdout) {
let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
slog_async::Async::new(drain)
.overflow_strategy(slog_async::OverflowStrategy::Block)
.build_no_guard()
} else {
let drain =
slog_bunyan::with_name("propolis-server", std::io::stdout())
.build()
.fuse();
slog_async::Async::new(drain)
.overflow_strategy(slog_async::OverflowStrategy::Block)
.build_no_guard()
};
let (dtrace_drain, probe_reg) = slog_dtrace::Dtrace::new();
let filtered_main = slog::LevelFilter::new(main_drain, level);
let log = slog::Logger::root(
slog::Duplicate::new(filtered_main.fuse(), dtrace_drain.fuse()).fuse(),
slog::o!(),
);
if let slog_dtrace::ProbeRegistration::Failed(err) = probe_reg {
slog::error!(&log, "Error registering slog-dtrace probes: {:?}", err);
}
log
}
fn is_valid_listen_addr_for_dns(listen_addr: IpAddr) -> bool {
let IpAddr::V6(addr) = listen_addr else {
return false;
};
addr != Ipv6Addr::LOCALHOST
}
/// Build metric configuration from the provided registration and listen
/// addresses.
///
/// This will return None if metrics are explicitly disabled.
fn build_metric_configuration(
log: &Logger,
metric_addr: MetricRegistration,
listen_addr: IpAddr,
) -> anyhow::Result<Option<MetricsEndpointConfig>> {
let cfg = match metric_addr {
MetricRegistration::Disable => {
info!(
log,
"metric registration is disabled, no metric \
data will be produced by this server",
);
None
}
MetricRegistration::Dns => {
anyhow::ensure!(
is_valid_listen_addr_for_dns(listen_addr),
"Metric registration can only use DNS \
if the Propolis server is provided a \
non-localhost IPv6 address"
);
Some(MetricsEndpointConfig { listen_addr, registration_addr: None })
}
MetricRegistration::WithAddr(addr) => Some(MetricsEndpointConfig {
listen_addr,
registration_addr: Some(addr),
}),
};
Ok(cfg)
}
fn main() -> anyhow::Result<()> {
// Ensure proper setup of USDT probes
register_probes().unwrap();
#[cfg(all(
feature = "omicron-build",
any(feature = "failure-injection", feature = "falcon")
))]
if option_env!("PHD_BUILD") != Some("true") {
panic!(
"`omicron-build` is enabled alongside development features, \
this build is NOT SUITABLE for production. Set PHD_BUILD=true in \
the environment and rebuild propolis-server if you really need \
this to work."
);
}
// Command line arguments.
let args = Args::parse();
match args {
Args::OpenApi => run_openapi()
.map_err(|e| anyhow!("Cannot generate OpenAPI spec: {}", e)),
Args::Run {
bootrom_path,
bootrom_version,
propolis_addr,
metric_addr,
vnc_addr,
log_level,
} => {
// Dropshot configuration.
let config_dropshot = ConfigDropshot {
bind_address: propolis_addr,
request_body_max_bytes: 1024 * 1024, // 1M for ISO bytes
default_handler_task_mode: HandlerTaskMode::Detached,
log_headers: vec![],
};
let log = build_logger(log_level);
let metric_config = build_metric_configuration(
&log,
metric_addr,
propolis_addr.ip(),
)?;
run_server(
bootrom_path,
bootrom_version,
config_dropshot,
metric_config,
vnc_addr,
log,
)
}
}
}