aboutsummaryrefslogtreecommitdiffstats
path: root/components/background_hang_monitor/tests/hang_monitor_tests.rs
blob: 36a6b45eec30ae1492d0f256a8fabd20ba0a15a8 (plain) (blame)
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
/* 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/. */

#![allow(unused_imports)]

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

use background_hang_monitor::HangMonitorRegister;
use background_hang_monitor_api::{
    BackgroundHangMonitorControlMsg, BackgroundHangMonitorExitSignal, HangAlert, HangAnnotation,
    HangMonitorAlert, MonitoredComponentId, MonitoredComponentType, ScriptHangAnnotation,
};
use base::id::TEST_PIPELINE_ID;
use ipc_channel::ipc;

lazy_static::lazy_static! {
    static ref SERIAL: Mutex<()> = Mutex::new(());
}

#[test]
fn test_hang_monitoring() {
    let _lock = SERIAL.lock().unwrap();

    let (background_hang_monitor_ipc_sender, background_hang_monitor_receiver) =
        ipc::channel().expect("ipc channel failure");
    let (_sampler_sender, sampler_receiver) = ipc::channel().expect("ipc channel failure");

    let background_hang_monitor_register = HangMonitorRegister::init(
        background_hang_monitor_ipc_sender.clone(),
        sampler_receiver,
        true,
    );
    let background_hang_monitor = background_hang_monitor_register.register_component(
        MonitoredComponentId(TEST_PIPELINE_ID, MonitoredComponentType::Script),
        Duration::from_millis(10),
        Duration::from_millis(1000),
        None,
    );

    // Start an activity.
    let hang_annotation = HangAnnotation::Script(ScriptHangAnnotation::AttachLayout);
    background_hang_monitor.notify_activity(hang_annotation);

    // Sleep until the "transient" timeout has been reached.
    thread::sleep(Duration::from_millis(10));

    // Check for a transient hang alert.
    match background_hang_monitor_receiver.recv().unwrap() {
        HangMonitorAlert::Hang(HangAlert::Transient(component_id, _annotation)) => {
            let expected = MonitoredComponentId(TEST_PIPELINE_ID, MonitoredComponentType::Script);
            assert_eq!(expected, component_id);
        },
        _ => unreachable!(),
    }

    // Sleep until the "permanent" timeout has been reached.
    thread::sleep(Duration::from_millis(1000));

    // Check for a permanent hang alert.
    match background_hang_monitor_receiver.recv().unwrap() {
        HangMonitorAlert::Hang(HangAlert::Permanent(component_id, _annotation, _profile)) => {
            let expected = MonitoredComponentId(TEST_PIPELINE_ID, MonitoredComponentType::Script);
            assert_eq!(expected, component_id);
        },
        _ => unreachable!(),
    }

    // Now the component is not hanging anymore.
    background_hang_monitor.notify_activity(hang_annotation);
    assert!(background_hang_monitor_receiver.try_recv().is_err());

    // Sleep for a while.
    thread::sleep(Duration::from_millis(10));

    // Check for a transient hang alert.
    match background_hang_monitor_receiver.recv().unwrap() {
        HangMonitorAlert::Hang(HangAlert::Transient(component_id, _annotation)) => {
            let expected = MonitoredComponentId(TEST_PIPELINE_ID, MonitoredComponentType::Script);
            assert_eq!(expected, component_id);
        },
        _ => unreachable!(),
    }

    // Now the component is waiting for a new task.
    background_hang_monitor.notify_wait();

    // Sleep for a while.
    thread::sleep(Duration::from_millis(100));

    // The component is still waiting, but not hanging.
    assert!(background_hang_monitor_receiver.try_recv().is_err());

    // New task handling starts.
    background_hang_monitor.notify_activity(hang_annotation);

    // Sleep for a while.
    thread::sleep(Duration::from_millis(10));

    // We're getting new hang alerts for the latest task.
    match background_hang_monitor_receiver.recv().unwrap() {
        HangMonitorAlert::Hang(HangAlert::Transient(component_id, _annotation)) => {
            let expected = MonitoredComponentId(TEST_PIPELINE_ID, MonitoredComponentType::Script);
            assert_eq!(expected, component_id);
        },
        _ => unreachable!(),
    }

    // No new alert yet
    assert!(background_hang_monitor_receiver.try_recv().is_err());

    // Shut-down the hang monitor
    drop(background_hang_monitor_register);
    drop(background_hang_monitor);

    // Sleep until the "max-timeout" has been reached.
    thread::sleep(Duration::from_millis(1000));

    // Still no new alerts because the hang monitor has shut-down already.
    assert!(background_hang_monitor_receiver.try_recv().is_err());
}

#[test]
// https://github.com/servo/servo/issues/28270
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
fn test_hang_monitoring_unregister() {
    let _lock = SERIAL.lock().unwrap();

    let (background_hang_monitor_ipc_sender, background_hang_monitor_receiver) =
        ipc::channel().expect("ipc channel failure");
    let (_sampler_sender, sampler_receiver) = ipc::channel().expect("ipc channel failure");

    let background_hang_monitor_register = HangMonitorRegister::init(
        background_hang_monitor_ipc_sender.clone(),
        sampler_receiver,
        true,
    );
    let background_hang_monitor = background_hang_monitor_register.register_component(
        MonitoredComponentId(TEST_PIPELINE_ID, MonitoredComponentType::Script),
        Duration::from_millis(10),
        Duration::from_millis(1000),
        None,
    );

    // Start an activity.
    let hang_annotation = HangAnnotation::Script(ScriptHangAnnotation::AttachLayout);
    background_hang_monitor.notify_activity(hang_annotation);

    // Unregister the component.
    background_hang_monitor.unregister();

    // Sleep until the "transient" timeout has been reached.
    thread::sleep(Duration::from_millis(10));

    // No new alert yet
    assert!(background_hang_monitor_receiver.try_recv().is_err());
}

// Perform two certain steps in `test_hang_monitoring_exit_signal_inner` in
// different orders to check for the race condition that
// caused <https://github.com/servo/servo/issues/28270> and
// <https://github.com/servo/servo/issues/27191>.
#[test]
fn test_hang_monitoring_exit_signal1() {
    test_hang_monitoring_exit_signal_inner(|e1, e2| {
        e1();
        thread::sleep(Duration::from_millis(100));
        e2();
    });
}

#[test]
fn test_hang_monitoring_exit_signal2() {
    test_hang_monitoring_exit_signal_inner(|e1, e2| {
        e1();
        e2();
    });
}

#[test]
fn test_hang_monitoring_exit_signal3() {
    test_hang_monitoring_exit_signal_inner(|e1, e2| {
        e2();
        e1();
    });
}

#[test]
fn test_hang_monitoring_exit_signal4() {
    test_hang_monitoring_exit_signal_inner(|e1, e2| {
        e2();
        thread::sleep(Duration::from_millis(100));
        e1();
    });
}

fn test_hang_monitoring_exit_signal_inner(op_order: fn(&mut dyn FnMut(), &mut dyn FnMut())) {
    let _lock = SERIAL.lock().unwrap();

    let (background_hang_monitor_ipc_sender, _background_hang_monitor_receiver) =
        ipc::channel().expect("ipc channel failure");
    let (control_sender, control_receiver) = ipc::channel().expect("ipc channel failure");

    struct BHMExitSignal {
        closing: Arc<AtomicBool>,
    }

    impl BackgroundHangMonitorExitSignal for BHMExitSignal {
        fn signal_to_exit(&self) {
            self.closing.store(true, Ordering::SeqCst);
        }
    }

    let closing = Arc::new(AtomicBool::new(false));
    let mut signal = Some(Box::new(BHMExitSignal {
        closing: closing.clone(),
    }));

    // Init a worker, without active monitoring.
    let background_hang_monitor_register = HangMonitorRegister::init(
        background_hang_monitor_ipc_sender.clone(),
        control_receiver,
        false,
    );

    let mut background_hang_monitor = None;
    let (exit_sender, exit_receiver) = ipc::channel().expect("Failed to create IPC channel!");
    let mut exit_sender = Some(exit_sender);

    // `op_order` determines the order in which these two closures are
    // executed.
    op_order(
        &mut || {
            // Register a component.
            background_hang_monitor = Some(background_hang_monitor_register.register_component(
                MonitoredComponentId(TEST_PIPELINE_ID, MonitoredComponentType::Script),
                Duration::from_millis(10),
                Duration::from_millis(1000),
                Some(signal.take().unwrap()),
            ));
        },
        &mut || {
            // Send the exit message.
            control_sender
                .send(BackgroundHangMonitorControlMsg::Exit(
                    exit_sender.take().unwrap(),
                ))
                .unwrap();
        },
    );

    // Assert we receive a confirmation back.
    assert!(exit_receiver.recv().is_ok());

    // Assert we get the exit signal.
    while !closing.load(Ordering::SeqCst) {
        thread::sleep(Duration::from_millis(10));
    }
}