-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathmod.rs
More file actions
401 lines (359 loc) · 14.7 KB
/
mod.rs
File metadata and controls
401 lines (359 loc) · 14.7 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
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
// 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/.
//! Routines to expose a connection to an instance's serial port.
use crate::migrate::MigrateError;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::num::NonZeroUsize;
use std::ops::Range;
use std::sync::Arc;
use std::time::Duration;
use crate::serial::history_buffer::{HistoryBuffer, SerialHistoryOffset};
use futures::future::Fuse;
use futures::stream::SplitSink;
use futures::{FutureExt, SinkExt, StreamExt};
use propolis::chardev::{pollers, Sink, Source};
use propolis_api_types::serial::InstanceSerialConsoleControlMessage;
use slog::{info, warn, Logger};
use thiserror::Error;
use tokio::sync::{mpsc, oneshot, Mutex, RwLock as AsyncRwLock};
use tokio::task::JoinHandle;
use tokio_tungstenite::tungstenite::protocol::{
frame::coding::CloseCode, CloseFrame,
};
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::{tungstenite, WebSocketStream};
pub(crate) mod history_buffer;
#[usdt::provider(provider = "propolis")]
mod probes {
fn serial_close_recv() {}
fn serial_new_ws() {}
fn serial_uart_write(n: usize) {}
fn serial_uart_out() {}
fn serial_uart_read(n: usize) {}
fn serial_inject_uart() {}
fn serial_ws_recv() {}
fn serial_buffer_size(n: usize) {}
}
/// Errors which may occur during the course of a serial connection.
#[derive(Error, Debug)]
pub enum SerialTaskError {
#[error("Cannot upgrade HTTP request to WebSockets: {0}")]
Upgrade(#[from] hyper::Error),
#[error("WebSocket Error: {0}")]
WebSocket(#[from] tungstenite::Error),
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
#[error("Mismatched websocket streams while closing")]
MismatchedStreams,
#[error("Error while waiting for notification: {0}")]
OneshotRecv(#[from] oneshot::error::RecvError),
#[error("JSON marshalling error while processing control message: {0}")]
Json(#[from] serde_json::Error),
}
pub enum SerialTaskControlMessage {
Stopping,
Migration { destination: SocketAddr, from_start: u64 },
}
pub struct SerialTask {
/// Handle to attached serial session
pub task: JoinHandle<()>,
/// Channel used to signal the task to terminate gracefully or notify
/// clients of a migration
pub control_ch: mpsc::Sender<SerialTaskControlMessage>,
/// Channel used to send new client connections to the streaming task
pub websocks_ch:
mpsc::Sender<WebSocketStream<dropshot::WebsocketConnectionRaw>>,
}
pub async fn instance_serial_task<Device: Sink + Source>(
mut websocks_recv: mpsc::Receiver<
WebSocketStream<dropshot::WebsocketConnectionRaw>,
>,
mut control_recv: mpsc::Receiver<SerialTaskControlMessage>,
serial: Arc<Serial<Device>>,
log: Logger,
) -> Result<(), SerialTaskError> {
info!(log, "Entered serial task");
let mut output = [0u8; 1024];
let mut cur_output: Option<Range<usize>> = None;
let mut cur_input: Option<(Vec<u8>, usize)> = None;
let mut ws_sinks: HashMap<
usize,
SplitSink<WebSocketStream<dropshot::WebsocketConnectionRaw>, Message>,
> = HashMap::new();
let mut ws_streams: HashMap<
usize,
futures::stream::SplitStream<
WebSocketStream<dropshot::WebsocketConnectionRaw>,
>,
> = HashMap::new();
let (send_ch, mut recv_ch) = mpsc::channel(4);
let mut next_stream_id = 0usize;
loop {
let (uart_read, ws_send) =
if ws_sinks.is_empty() || cur_output.is_none() {
(serial.read_source(&mut output).fuse(), Fuse::terminated())
} else {
let range = cur_output.clone().unwrap();
(
Fuse::terminated(),
if !ws_sinks.is_empty() {
futures::stream::iter(
ws_sinks.iter_mut().zip(std::iter::repeat(
Vec::from(&output[range]),
)),
)
.for_each_concurrent(4, |((_i, ws), bin)| {
ws.send(Message::binary(bin)).map(|_| ())
})
.fuse()
} else {
Fuse::terminated()
},
)
};
let (ws_recv, uart_write) = match &cur_input {
None => (
if !ws_streams.is_empty() {
futures::stream::iter(ws_streams.iter_mut())
.for_each_concurrent(4, |(i, ws)| {
ws.next()
.then(|msg| send_ch.send((*i, msg)))
.map(|_| ())
})
.fuse()
} else {
Fuse::terminated()
},
Fuse::terminated(),
),
Some((data, consumed)) => (
Fuse::terminated(),
serial.write_sink(&data[*consumed..]).fuse(),
),
};
let input_recv_ch_fut = recv_ch.recv().fuse();
let new_ws_recv = websocks_recv.recv().fuse();
let control_recv_fut = control_recv.recv().fuse();
tokio::select! {
// Poll in the order written
biased;
// It's important we always poll the close channel first
// so that a constant stream of incoming/outgoing messages
// don't cause us to ignore it
message = control_recv_fut => {
probes::serial_close_recv!(|| {});
match message {
Some(SerialTaskControlMessage::Stopping) | None => {
// Gracefully close the connections to any clients
for (i, ws0) in ws_sinks.into_iter() {
let ws1 = ws_streams.remove(&i).ok_or(SerialTaskError::MismatchedStreams)?;
let mut ws = ws0.reunite(ws1).map_err(|_| SerialTaskError::MismatchedStreams)?;
let _ = ws.close(Some(CloseFrame {
code: CloseCode::Away,
reason: "VM stopped".into(),
})).await;
}
}
Some(SerialTaskControlMessage::Migration { destination, from_start }) => {
let mut failures = 0;
for sink in ws_sinks.values_mut() {
if sink.send(Message::Text(serde_json::to_string(
&InstanceSerialConsoleControlMessage::Migrating {
destination,
from_start,
}
)?)).await.is_err() {
failures += 1;
}
}
if failures > 0 {
warn!(log, "Failed to send migration info to {} connected clients.", failures);
}
}
}
info!(log, "Terminating serial task");
break;
}
new_ws = new_ws_recv => {
probes::serial_new_ws!(|| {});
if let Some(ws) = new_ws {
let (ws_sink, ws_stream) = ws.split();
ws_sinks.insert(next_stream_id, ws_sink);
ws_streams.insert(next_stream_id, ws_stream);
next_stream_id += 1;
}
}
// Write bytes into the UART from the WS
written = uart_write => {
probes::serial_uart_write!(|| { written.unwrap_or(0) });
match written {
Some(0) | None => {
break;
}
Some(n) => {
let (data, consumed) = cur_input.as_mut().unwrap();
*consumed += n;
if *consumed == data.len() {
cur_input = None;
}
}
}
}
// Transmit bytes from the UART through the WS
_ = ws_send => {
probes::serial_uart_out!(|| {});
cur_output = None;
}
// Read bytes from the UART to be transmitted out the WS
nread = uart_read => {
// N.B. Putting this probe inside the match arms below causes
// the `break` arm to be taken unexpectedly. See
// propolis#292 for details.
probes::serial_uart_read!(|| { nread.unwrap_or(0) });
match nread {
Some(0) | None => {
break;
}
Some(n) => {
cur_output = Some(0..n)
}
}
}
// Receive bytes from the intermediate channel to be injected into
// the UART. This needs to be checked before `ws_recv` so that
// "close" messages can be processed and their indicated
// sinks/streams removed before they are polled again.
pair = input_recv_ch_fut => {
probes::serial_inject_uart!(|| {});
if let Some((i, msg)) = pair {
match msg {
Some(Ok(Message::Binary(input))) => {
cur_input = Some((input, 0));
}
Some(Ok(Message::Close(..))) | None => {
info!(log, "Removing closed serial connection {}.", i);
let sink = ws_sinks.remove(&i).ok_or(SerialTaskError::MismatchedStreams)?;
let stream = ws_streams.remove(&i).ok_or(SerialTaskError::MismatchedStreams)?;
if let Err(e) = sink.reunite(stream).map_err(|_| SerialTaskError::MismatchedStreams)?.close(None).await {
warn!(log, "Failed while closing stream {}: {}", i, e);
}
},
_ => continue,
}
}
}
// Receive bytes from connected WS clients to feed to the
// intermediate recv_ch
_ = ws_recv => {
probes::serial_ws_recv!(|| {});
}
}
}
info!(log, "Returning from serial task");
Ok(())
}
/// Represents a serial connection into the VM.
pub struct Serial<Device: Sink + Source> {
uart: Arc<Device>,
task_control_ch: Mutex<Option<mpsc::Sender<SerialTaskControlMessage>>>,
sink_poller: Arc<pollers::SinkBuffer>,
source_poller: Arc<pollers::SourceBuffer>,
history: AsyncRwLock<HistoryBuffer>,
}
impl<Device: Sink + Source> Serial<Device> {
/// Creates a new buffered serial connection on top of `uart.`
///
/// Creation of this object disables "autodiscard", and destruction
/// of the object re-enables "autodiscard" mode.
///
/// # Arguments
///
/// * `uart` - The device which data will be read from / written to.
/// * `sink_size` - A lower bound on the size of the writeback buffer.
/// * `source_size` - A lower bound on the size of the read buffer.
pub fn new(
uart: Arc<Device>,
sink_size: NonZeroUsize,
source_size: NonZeroUsize,
) -> Serial<Device> {
let sink_poller = pollers::SinkBuffer::new(sink_size);
let source_poller = pollers::SourceBuffer::new(pollers::Params {
buf_size: source_size,
poll_interval: Duration::from_millis(10),
poll_miss_thresh: 5,
});
let history = Default::default();
sink_poller.attach(uart.as_ref());
source_poller.attach(uart.as_ref());
uart.set_autodiscard(false);
let task_control_ch = Default::default();
Serial { uart, task_control_ch, sink_poller, source_poller, history }
}
pub async fn read_source(&self, buf: &mut [u8]) -> Option<usize> {
let uart = self.uart.clone();
let bytes_read = self.source_poller.read(buf, uart.as_ref()).await?;
self.history.write().await.consume(&buf[..bytes_read]);
Some(bytes_read)
}
pub async fn write_sink(&self, buf: &[u8]) -> Option<usize> {
let uart = self.uart.clone();
self.sink_poller.write(buf, uart.as_ref()).await
}
pub(crate) async fn history_vec(
&self,
byte_offset: SerialHistoryOffset,
max_bytes: Option<usize>,
) -> Result<(Vec<u8>, usize), history_buffer::Error> {
self.history.read().await.contents_vec(byte_offset, max_bytes)
}
// provide the channel through which we inform connected websocket clients
// that a migration has occurred, and where to reconnect.
// (the server's serial-to-websocket task -- and thus the receiving end of
// this channel -- are spawned in `instance_ensure_common`, after the
// construction of `Serial`)
pub(crate) async fn set_task_control_sender(
&self,
control_ch: mpsc::Sender<SerialTaskControlMessage>,
) {
self.task_control_ch.lock().await.replace(control_ch);
}
pub(crate) async fn export_history(
&self,
destination: SocketAddr,
) -> Result<String, MigrateError> {
let read_hist = self.history.read().await;
let from_start = read_hist.bytes_from_start() as u64;
let encoded = ron::to_string(&*read_hist)
.map_err(|e| MigrateError::Codec(e.to_string()))?;
drop(read_hist);
if let Some(ch) = self.task_control_ch.lock().await.as_ref() {
ch.send(SerialTaskControlMessage::Migration {
destination,
from_start,
})
.await
.map_err(|_| MigrateError::InvalidInstanceState)?;
}
Ok(encoded)
}
pub(crate) async fn import(
&self,
serialized_hist: &str,
) -> Result<(), MigrateError> {
self.sink_poller.attach(self.uart.as_ref());
self.source_poller.attach(self.uart.as_ref());
self.uart.set_autodiscard(false);
let decoded = ron::from_str(serialized_hist)
.map_err(|e| MigrateError::Codec(e.to_string()))?;
let mut write_hist = self.history.write().await;
*write_hist = decoded;
Ok(())
}
}
impl<Device: Sink + Source> Drop for Serial<Device> {
fn drop(&mut self) {
self.uart.set_autodiscard(true);
}
}