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
use std::future::Future;
use k8s_openapi::apimachinery::pkg::apis::meta::v1::Status;
use futures::{
channel::oneshot,
future::{
select,
Either::{Left, Right},
},
FutureExt, SinkExt, StreamExt,
};
use thiserror::Error;
use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt, DuplexStream};
use tokio_tungstenite::{tungstenite as ws, WebSocketStream};
use super::AttachParams;
type StatusReceiver = oneshot::Receiver<Status>;
type StatusSender = oneshot::Sender<Status>;
#[derive(Debug, Error)]
pub enum Error {
#[error("failed to read from stdin: {0}")]
ReadStdin(#[source] std::io::Error),
#[error("failed to send a stdin data: {0}")]
SendStdin(#[source] ws::Error),
#[error("failed to write to stdout: {0}")]
WriteStdout(#[source] std::io::Error),
#[error("failed to write to stderr: {0}")]
WriteStderr(#[source] std::io::Error),
#[error("failed to receive a WebSocket message: {0}")]
ReceiveWebSocketMessage(#[source] ws::Error),
#[error("failed to complete the background task: {0}")]
Spawn(#[source] tokio::task::JoinError),
#[error("failed to send a WebSocket close message: {0}")]
SendClose(#[source] ws::Error),
#[error("failed to deserialize status object: {0}")]
DeserializeStatus(#[source] serde_json::Error),
#[error("failed to send status object")]
SendStatus,
}
const MAX_BUF_SIZE: usize = 1024;
#[cfg_attr(docsrs, doc(cfg(feature = "ws")))]
pub struct AttachedProcess {
has_stdin: bool,
has_stdout: bool,
has_stderr: bool,
stdin_writer: Option<DuplexStream>,
stdout_reader: Option<DuplexStream>,
stderr_reader: Option<DuplexStream>,
status_rx: Option<StatusReceiver>,
task: tokio::task::JoinHandle<Result<(), Error>>,
}
impl AttachedProcess {
pub(crate) fn new<S>(stream: WebSocketStream<S>, ap: &AttachParams) -> Self
where
S: AsyncRead + AsyncWrite + Unpin + Sized + Send + 'static,
{
let (stdin_writer, stdin_reader) = tokio::io::duplex(ap.max_stdin_buf_size.unwrap_or(MAX_BUF_SIZE));
let (stdout_writer, stdout_reader) = if ap.stdout {
let (w, r) = tokio::io::duplex(ap.max_stdout_buf_size.unwrap_or(MAX_BUF_SIZE));
(Some(w), Some(r))
} else {
(None, None)
};
let (stderr_writer, stderr_reader) = if ap.stderr {
let (w, r) = tokio::io::duplex(ap.max_stderr_buf_size.unwrap_or(MAX_BUF_SIZE));
(Some(w), Some(r))
} else {
(None, None)
};
let (status_tx, status_rx) = oneshot::channel();
let task = tokio::spawn(start_message_loop(
stream,
stdin_reader,
stdout_writer,
stderr_writer,
status_tx,
));
AttachedProcess {
has_stdin: ap.stdin,
has_stdout: ap.stdout,
has_stderr: ap.stderr,
task,
stdin_writer: Some(stdin_writer),
stdout_reader,
stderr_reader,
status_rx: Some(status_rx),
}
}
pub fn stdin(&mut self) -> Option<impl AsyncWrite + Unpin> {
if !self.has_stdin {
return None;
}
self.stdin_writer.take()
}
pub fn stdout(&mut self) -> Option<impl AsyncRead + Unpin> {
if !self.has_stdout {
return None;
}
self.stdout_reader.take()
}
pub fn stderr(&mut self) -> Option<impl AsyncRead + Unpin> {
if !self.has_stderr {
return None;
}
self.stderr_reader.take()
}
#[inline]
pub fn abort(&self) {
self.task.abort();
}
pub async fn join(self) -> Result<(), Error> {
self.task.await.unwrap_or_else(|e| Err(Error::Spawn(e)))
}
pub fn take_status(&mut self) -> Option<impl Future<Output = Option<Status>>> {
self.status_rx.take().map(|recv| recv.map(|res| res.ok()))
}
}
const STDIN_CHANNEL: u8 = 0;
const STDOUT_CHANNEL: u8 = 1;
const STDERR_CHANNEL: u8 = 2;
const STATUS_CHANNEL: u8 = 3;
async fn start_message_loop<S>(
stream: WebSocketStream<S>,
stdin: impl AsyncRead + Unpin,
mut stdout: Option<impl AsyncWrite + Unpin>,
mut stderr: Option<impl AsyncWrite + Unpin>,
status_tx: StatusSender,
) -> Result<(), Error>
where
S: AsyncRead + AsyncWrite + Unpin + Sized + Send + 'static,
{
let mut stdin_stream = tokio_util::io::ReaderStream::new(stdin);
let (mut server_send, raw_server_recv) = stream.split();
let mut server_recv = raw_server_recv.filter_map(filter_message).boxed();
let mut server_msg = server_recv.next();
let mut next_stdin = stdin_stream.next();
loop {
match select(server_msg, next_stdin).await {
Left((Some(message), p_next_stdin)) => {
match message {
Ok(Message::Stdout(bin)) => {
if let Some(stdout) = stdout.as_mut() {
stdout.write_all(&bin[1..]).await.map_err(Error::WriteStdout)?;
}
}
Ok(Message::Stderr(bin)) => {
if let Some(stderr) = stderr.as_mut() {
stderr.write_all(&bin[1..]).await.map_err(Error::WriteStderr)?;
}
}
Ok(Message::Status(bin)) => {
let status =
serde_json::from_slice::<Status>(&bin[1..]).map_err(Error::DeserializeStatus)?;
status_tx.send(status).map_err(|_| Error::SendStatus)?;
break;
}
Err(err) => {
return Err(Error::ReceiveWebSocketMessage(err));
}
}
server_msg = server_recv.next();
next_stdin = p_next_stdin;
}
Left((None, _)) => {
break;
}
Right((Some(Ok(bytes)), p_server_msg)) => {
if !bytes.is_empty() {
let mut vec = Vec::with_capacity(bytes.len() + 1);
vec.push(STDIN_CHANNEL);
vec.extend_from_slice(&bytes[..]);
server_send
.send(ws::Message::binary(vec))
.await
.map_err(Error::SendStdin)?;
}
server_msg = p_server_msg;
next_stdin = stdin_stream.next();
}
Right((Some(Err(err)), _)) => {
return Err(Error::ReadStdin(err));
}
Right((None, _)) => {
server_send.close().await.map_err(Error::SendClose)?;
break;
}
}
}
Ok(())
}
enum Message {
Stdout(Vec<u8>),
Stderr(Vec<u8>),
Status(Vec<u8>),
}
async fn filter_message(wsm: Result<ws::Message, ws::Error>) -> Option<Result<Message, ws::Error>> {
match wsm {
Ok(ws::Message::Binary(bin)) if bin.len() > 1 => match bin[0] {
STDOUT_CHANNEL => Some(Ok(Message::Stdout(bin))),
STDERR_CHANNEL => Some(Ok(Message::Stderr(bin))),
STATUS_CHANNEL => Some(Ok(Message::Status(bin))),
_ => None,
},
Ok(_) => None,
Err(err) => Some(Err(err)),
}
}