nextest_runner/
signal.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
// Copyright (c) The nextest Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Support for handling signals in nextest.

use crate::errors::SignalHandlerSetupError;

/// The kind of signal handling to set up for a test run.
///
/// A `SignalHandlerKind` can be passed into
/// [`TestRunnerBuilder::build`](crate::runner::TestRunnerBuilder::build).
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum SignalHandlerKind {
    /// The standard signal handler. Capture interrupt and termination signals depending on the
    /// platform.
    Standard,

    /// A no-op signal handler. Useful for tests.
    Noop,
}

impl SignalHandlerKind {
    pub(crate) fn build(self) -> Result<SignalHandler, SignalHandlerSetupError> {
        match self {
            Self::Standard => SignalHandler::new(),
            Self::Noop => Ok(SignalHandler::noop()),
        }
    }
}

/// The signal handler implementation.
#[derive(Debug)]
pub(crate) struct SignalHandler {
    signals: Option<imp::Signals>,
}

impl SignalHandler {
    /// Creates a new `SignalHandler` that handles Ctrl-C and other signals.
    #[cfg(any(unix, windows))]
    pub(crate) fn new() -> Result<Self, SignalHandlerSetupError> {
        let signals = imp::Signals::new()?;
        Ok(Self {
            signals: Some(signals),
        })
    }

    /// Creates a new `SignalReceiver` that does nothing.
    pub(crate) fn noop() -> Self {
        Self { signals: None }
    }

    pub(crate) async fn recv(&mut self) -> Option<SignalEvent> {
        match &mut self.signals {
            Some(signals) => signals.recv().await,
            None => None,
        }
    }
}

#[cfg(unix)]
mod imp {
    use super::*;
    use std::io;
    use tokio::signal::unix::{signal, SignalKind};
    use tokio_stream::{wrappers::SignalStream, StreamExt, StreamMap};

    #[derive(Clone, Copy, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
    enum SignalId {
        Int,
        Hup,
        Term,
        Quit,
        Tstp,
        Cont,
        Info,
        Usr1,
    }

    /// Signals for SIGINT, SIGTERM and SIGHUP on Unix.
    #[derive(Debug)]
    pub(super) struct Signals {
        // The number of streams is quite small, so a StreamMap (backed by a
        // Vec) is a good option to store the list of streams to poll.
        map: StreamMap<SignalId, SignalStream>,
        sigquit_as_info: bool,
    }

    impl Signals {
        pub(super) fn new() -> io::Result<Self> {
            let mut map = StreamMap::new();

            // Set up basic signals.
            map.extend([
                (SignalId::Int, signal_stream(SignalKind::interrupt())?),
                (SignalId::Hup, signal_stream(SignalKind::hangup())?),
                (SignalId::Term, signal_stream(SignalKind::terminate())?),
                (SignalId::Quit, signal_stream(SignalKind::quit())?),
                (SignalId::Tstp, signal_stream(tstp_kind())?),
                (SignalId::Cont, signal_stream(cont_kind())?),
                (SignalId::Usr1, signal_stream(SignalKind::user_defined1())?),
            ]);

            if let Some(info_kind) = info_kind() {
                map.insert(SignalId::Info, signal_stream(info_kind)?);
            }

            // This is a debug-only environment variable to let ctrl-\ (SIGQUIT)
            // behave like SIGINFO. Useful for testing signal-based info queries
            // on Linux.
            let sigquit_as_info =
                std::env::var("__NEXTEST_SIGQUIT_AS_INFO").map_or(false, |v| v == "1");

            Ok(Self {
                map,
                sigquit_as_info,
            })
        }

        pub(super) async fn recv(&mut self) -> Option<SignalEvent> {
            self.map.next().await.map(|(id, _)| match id {
                SignalId::Int => SignalEvent::Shutdown(ShutdownEvent::Interrupt),
                SignalId::Hup => SignalEvent::Shutdown(ShutdownEvent::Hangup),
                SignalId::Term => SignalEvent::Shutdown(ShutdownEvent::Term),
                SignalId::Quit => {
                    if self.sigquit_as_info {
                        SignalEvent::Info(SignalInfoEvent::Info)
                    } else {
                        SignalEvent::Shutdown(ShutdownEvent::Quit)
                    }
                }
                SignalId::Tstp => SignalEvent::JobControl(JobControlEvent::Stop),
                SignalId::Cont => SignalEvent::JobControl(JobControlEvent::Continue),
                SignalId::Info => SignalEvent::Info(SignalInfoEvent::Info),
                SignalId::Usr1 => SignalEvent::Info(SignalInfoEvent::Usr1),
            })
        }
    }

    fn signal_stream(kind: SignalKind) -> io::Result<SignalStream> {
        Ok(SignalStream::new(signal(kind)?))
    }

    fn tstp_kind() -> SignalKind {
        SignalKind::from_raw(libc::SIGTSTP)
    }

    fn cont_kind() -> SignalKind {
        SignalKind::from_raw(libc::SIGCONT)
    }

    // The SIGINFO signal is available on many Unix platforms, but not all of
    // them.
    cfg_if::cfg_if! {
        if #[cfg(any(
            target_os = "dragonfly",
            target_os = "freebsd",
            target_os = "macos",
            target_os = "netbsd",
            target_os = "openbsd",
            // TODO: add illumos once
            // https://github.com/tokio-rs/tokio/pull/6995 is in a released
            // version of Tokio.
        ))] {
            fn info_kind() -> Option<SignalKind> {
                Some(SignalKind::info())
            }
        } else {
            fn info_kind() -> Option<SignalKind> {
                None
            }
        }
    }
}

#[cfg(windows)]
mod imp {
    use super::*;
    use tokio::signal::windows::{ctrl_c, CtrlC};

    #[derive(Debug)]
    pub(super) struct Signals {
        ctrl_c: CtrlC,
        ctrl_c_done: bool,
    }

    impl Signals {
        pub(super) fn new() -> std::io::Result<Self> {
            let ctrl_c = ctrl_c()?;
            Ok(Self {
                ctrl_c,
                ctrl_c_done: false,
            })
        }

        pub(super) async fn recv(&mut self) -> Option<SignalEvent> {
            if self.ctrl_c_done {
                return None;
            }

            match self.ctrl_c.recv().await {
                Some(()) => Some(SignalEvent::Shutdown(ShutdownEvent::Interrupt)),
                None => {
                    self.ctrl_c_done = true;
                    None
                }
            }
        }
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum SignalEvent {
    #[cfg(unix)]
    JobControl(JobControlEvent),
    Shutdown(ShutdownEvent),
    #[cfg_attr(not(unix), expect(dead_code))]
    Info(SignalInfoEvent),
}

// A job-control related signal event.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum JobControlEvent {
    #[cfg(unix)]
    Stop,
    #[cfg(unix)]
    Continue,
}

// A signal event that should cause a shutdown to happen.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum ShutdownEvent {
    #[cfg(unix)]
    Hangup,
    #[cfg(unix)]
    Term,
    #[cfg(unix)]
    Quit,
    Interrupt,
}

impl ShutdownEvent {
    #[cfg(test)]
    pub(crate) const ALL_VARIANTS: &'static [Self] = &[
        #[cfg(unix)]
        Self::Hangup,
        #[cfg(unix)]
        Self::Term,
        #[cfg(unix)]
        Self::Quit,
        Self::Interrupt,
    ];
}

// A signal event to query information about tests.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) enum SignalInfoEvent {
    /// SIGUSR1
    #[cfg(unix)]
    Usr1,

    /// SIGINFO
    #[cfg(unix)]
    Info,
}