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
pub mod restart_coordination_socket;
pub mod shutdown;
mod pipes;
pub use shutdown::{ShutdownCoordinator, ShutdownHandle, ShutdownSignal};
use crate::restart_coordination_socket::{
RestartCoordinationSocket, RestartMessage, RestartRequest, RestartResponse,
};
use anyhow::anyhow;
use futures::stream::{Stream, StreamExt};
use serde::Deserialize;
use std::env;
use std::fs::remove_file;
use std::future::Future;
use std::io;
use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
use std::os::unix::net::UnixListener as StdUnixListener;
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process;
use std::thread;
use thiserror::Error;
use tokio::net::{UnixListener, UnixStream};
use tokio::select;
use tokio::signal::unix::{signal, Signal, SignalKind};
use tokio::sync::mpsc::{channel, Receiver, Sender};
use tokio_stream::wrappers::UnixListenerStream;
pub type RestartResult<T> = anyhow::Result<T>;
const ENV_NOTIFY_SOCKET: &str = "OXY_NOTIFY_SOCKET";
const ENV_RESTART_SOCKET: &str = "OXY_RESTART_SOCKET";
const ENV_SYSTEMD_PID: &str = "LISTEN_PID";
const REBIND_SYSTEMD_PID: &str = "auto";
#[derive(Clone, Debug, Deserialize)]
pub struct RestartConfig {
pub enabled: bool,
pub coordination_socket_path: PathBuf,
}
impl RestartConfig {
pub fn try_into_restart_task(self) -> io::Result<(impl Future<Output = RestartResult<()>> + Send)> {
fixup_systemd_env();
spawn_restart_task(&self)
}
pub async fn request_restart(self) -> RestartResult<u32> {
if !self.enabled {
return Err(anyhow!(
"no restart coordination socket socket defined in config"
));
}
let socket = UnixStream::connect(self.coordination_socket_path).await?;
restart_coordination_socket::RestartCoordinationSocket::new(socket)
.send_restart_command()
.await
}
pub fn request_restart_sync(self) -> RestartResult<u32> {
tokio::runtime::Runtime::new()
.unwrap()
.block_on(self.request_restart())
}
}
pub fn fixup_systemd_env() {
#[cfg(target_os = "linux")]
if let Ok(true) = env::var(ENV_SYSTEMD_PID).map(|p| p == REBIND_SYSTEMD_PID) {
env::set_var(ENV_SYSTEMD_PID, process::id().to_string());
}
}
pub fn startup_complete() -> io::Result<()> {
if let Ok(notify_fd) = env::var(ENV_NOTIFY_SOCKET) {
pipes::CompletionSender::from_fd_string(¬ify_fd)?.send()?;
}
env::remove_var(ENV_NOTIFY_SOCKET);
let _ = sd_notify::notify(false, &[sd_notify::NotifyState::Ready]);
Ok(())
}
struct RestartResponder {
rpc: Option<RestartCoordinationSocket>,
}
impl RestartResponder {
async fn respond(self, result: Result<u32, String>) {
let response = match result {
Ok(pid) => RestartResponse::RestartComplete(pid),
Err(e) => RestartResponse::RestartFailed(e),
};
if let Some(mut rpc) = self.rpc {
if let Err(e) = rpc.send_message(RestartMessage::Response(response)).await {
log::warn!("Failed to respond to restart coordinator: {}", e);
}
}
}
}
pub fn spawn_restart_task(
settings: &RestartConfig,
) -> io::Result<impl Future<Output = RestartResult<()>> + Send> {
let socket = match settings.enabled {
true => Some(settings.coordination_socket_path.as_ref()),
false => None,
};
let mut signal_stream = signal(SignalKind::user_defined1())?;
let (restart_fd, mut socket_stream) = new_restart_coordination_socket_stream(socket)?;
let mut child_spawner = ChildSpawner::new(restart_fd);
Ok(async move {
startup_complete()?;
loop {
let responder = next_restart_request(&mut signal_stream, &mut socket_stream).await?;
log::debug!("Spawning new process");
let res = child_spawner.spawn_new_process().await;
responder
.respond(res.as_ref().map(|p| *p).map_err(|e| e.to_string()))
.await;
match res {
Ok(pid) => {
log::debug!("New process spawned with pid {}", pid);
if let Err(e) = sd_notify::notify(true, &[sd_notify::NotifyState::MainPid(pid)])
{
log::error!("Failed to notify systemd: {}", e);
}
return Ok(());
}
Err(ChildSpawnError::ChildError(e)) => {
log::error!("Restart failed: {}", e);
}
Err(ChildSpawnError::RestartThreadGone) => {
res?;
}
}
}
})
}
struct ChildSpawner {
signal_sender: Sender<()>,
pid_receiver: Receiver<io::Result<process::Child>>,
}
impl ChildSpawner {
fn new(restart_fd: Option<RawFd>) -> Self {
let (signal_sender, mut signal_receiver) = channel(1);
let (pid_sender, pid_receiver) = channel(1);
thread::spawn(move || {
while let Some(()) = signal_receiver.blocking_recv() {
pid_sender
.blocking_send(spawn_child(restart_fd))
.expect("parent needs to receive the child");
}
});
ChildSpawner {
signal_sender,
pid_receiver,
}
}
async fn spawn_new_process(&mut self) -> Result<u32, ChildSpawnError> {
self.signal_sender
.send(())
.await
.map_err(|_| ChildSpawnError::RestartThreadGone)?;
match self.pid_receiver.recv().await {
Some(Ok(child)) => Ok(child.id()),
Some(Err(e)) => Err(ChildSpawnError::ChildError(e)),
None => Err(ChildSpawnError::RestartThreadGone),
}
}
}
#[derive(Error, Debug)]
pub enum ChildSpawnError {
#[error("Restart thread exited")]
RestartThreadGone,
#[error("Child failed to start: {0}")]
ChildError(io::Error),
}
async fn next_restart_request(
signal_stream: &mut Signal,
mut socket_stream: impl Stream<Item = RestartResponder> + Unpin,
) -> RestartResult<RestartResponder> {
select! {
_ = signal_stream.recv() => Ok(RestartResponder{ rpc: None }),
r = socket_stream.next() => match r {
Some(r) => Ok(r),
None => {
Err(anyhow!("Restart coordinator socket acceptor terminated"))
}
}
}
}
fn new_restart_coordination_socket_stream(
restart_coordination_socket: Option<&Path>,
) -> io::Result<(Option<RawFd>, impl Stream<Item = RestartResponder>)> {
if let Some(path) = restart_coordination_socket {
let listener = bind_restart_coordination_socket(path)?;
let fd = listener.as_raw_fd();
let st = listen_for_restart_events(listener);
Ok((Some(fd), st.boxed()))
} else {
Ok((None, futures::stream::pending().boxed()))
}
}
fn bind_restart_coordination_socket(path: &Path) -> io::Result<UnixListener> {
match env::var(ENV_RESTART_SOCKET) {
Err(_) => {
let _ = remove_file(path);
UnixListener::bind(path)
}
Ok(maybe_sock_fd) => match maybe_sock_fd.parse() {
Ok(fd) => {
Ok(UnixListener::from_std(unsafe { StdUnixListener::from_raw_fd(fd) }).unwrap())
}
Err(_) => Err(io::Error::new(
io::ErrorKind::Other,
"inherited restart coordination socket is not an fd",
)),
},
}
}
fn listen_for_restart_events(
restart_coordination_socket: UnixListener,
) -> impl Stream<Item = RestartResponder> {
UnixListenerStream::new(restart_coordination_socket).filter_map(move |r| async move {
let sock = match r {
Ok(sock) => sock,
Err(e) => {
log::error!("Restart coordination socket accept error: {}", e);
return None;
}
};
let mut rpc = RestartCoordinationSocket::new(sock);
match rpc.receive_message().await {
Ok(RestartMessage::Request(RestartRequest::TryRestart)) => {
Some(RestartResponder { rpc: Some(rpc) })
}
Ok(m) => {
log::warn!(
"Restart coordination socket received unexpected message: {:?}",
m
);
None
}
Err(e) => {
log::warn!("Restart coordination socket connection error: {}", e);
None
}
}
})
}
fn clear_cloexec(fd: RawFd) -> nix::Result<()> {
use nix::fcntl::*;
let mut current_flags = FdFlag::from_bits_truncate(fcntl(fd, FcntlArg::F_GETFD)?);
current_flags.remove(FdFlag::FD_CLOEXEC);
fcntl(fd, FcntlArg::F_SETFD(current_flags))?;
Ok(())
}
fn spawn_child(restart_fd: Option<RawFd>) -> io::Result<process::Child> {
let mut args = env::args();
let process_name = args.next().unwrap();
let (mut notif_r, notif_w) = pipes::pipe_pair()?;
let mut cmd = process::Command::new(process_name);
cmd.args(args)
.env(ENV_SYSTEMD_PID, REBIND_SYSTEMD_PID)
.env(ENV_NOTIFY_SOCKET, notif_w.fd_string());
if let Some(fd) = restart_fd {
unsafe {
cmd.env(ENV_RESTART_SOCKET, fd.to_string())
.pre_exec(move || {
clear_cloexec(fd)?;
Ok(())
});
}
}
let child = cmd.spawn()?;
drop(notif_w);
notif_r.recv()?;
Ok(child)
}