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
use crate::runtime::execution::Execution;
use crate::runtime::task::TaskId;
use crate::runtime::thread::continuation::{ContinuationPool, CONTINUATION_POOL};
use crate::scheduler::metrics::MetricsScheduler;
use crate::scheduler::{Schedule, Scheduler};
use crate::Config;
use std::cell::RefCell;
use std::panic;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::sync::Arc;
use std::thread;
use std::time::Instant;
use tracing::{span, Level};
#[derive(Debug)]
pub struct Runner<S: ?Sized + Scheduler> {
scheduler: Rc<RefCell<MetricsScheduler<S>>>,
config: Config,
}
impl<S: Scheduler + 'static> Runner<S> {
pub fn new(scheduler: S, config: Config) -> Self {
let metrics_scheduler = MetricsScheduler::new(scheduler);
Self {
scheduler: Rc::new(RefCell::new(metrics_scheduler)),
config,
}
}
pub fn run<F>(self, f: F) -> usize
where
F: Fn() + Send + Sync + 'static,
{
CONTINUATION_POOL.set(&ContinuationPool::new(), || {
let f = Arc::new(f);
let start = Instant::now();
let mut i = 0;
loop {
if self.config.max_time.map(|t| start.elapsed() > t).unwrap_or(false) {
break;
}
let schedule = match self.scheduler.borrow_mut().new_execution() {
None => break,
Some(s) => s,
};
let execution = Execution::new(self.scheduler.clone(), schedule);
let f = Arc::clone(&f);
span!(Level::INFO, "execution", i).in_scope(|| execution.run(&self.config, move || f()));
i += 1;
}
i
})
}
}
#[derive(Debug)]
pub struct PortfolioRunner {
schedulers: Vec<Box<dyn Scheduler + Send + 'static>>,
stop_on_first_failure: bool,
config: Config,
}
impl PortfolioRunner {
pub fn new(stop_on_first_failure: bool, config: Config) -> Self {
Self {
schedulers: Vec::new(),
stop_on_first_failure,
config,
}
}
pub fn add(&mut self, scheduler: impl Scheduler + Send + 'static) {
self.schedulers.push(Box::new(scheduler));
}
pub fn run<F>(self, f: F)
where
F: Fn() + Send + Sync + Clone + 'static,
{
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ThreadResult {
Passed,
Failed,
}
let (tx, rx) = mpsc::sync_channel::<ThreadResult>(0);
let stop_signal = Arc::new(AtomicBool::new(false));
let config = self.config;
let threads = self
.schedulers
.into_iter()
.enumerate()
.map(|(i, scheduler)| {
let f = f.clone();
let tx = tx.clone();
let stop_signal = stop_signal.clone();
let config = config.clone();
thread::spawn(move || {
let scheduler = PortfolioStoppableScheduler { scheduler, stop_signal };
let runner = Runner::new(scheduler, config);
span!(Level::INFO, "job", i).in_scope(|| {
let ret = panic::catch_unwind(panic::AssertUnwindSafe(|| runner.run(f)));
match ret {
Ok(_) => tx.send(ThreadResult::Passed),
Err(e) => {
tx.send(ThreadResult::Failed).unwrap();
panic::resume_unwind(e);
}
}
})
})
})
.collect::<Vec<_>>();
for _ in 0..threads.len() {
if rx.recv().unwrap() == ThreadResult::Failed && self.stop_on_first_failure {
stop_signal.store(true, Ordering::SeqCst);
}
}
let mut panic = None;
for thread in threads {
if let Err(e) = thread.join() {
panic = Some(e);
}
}
assert!(stop_signal.load(Ordering::SeqCst) == panic.is_some());
if let Some(e) = panic {
std::panic::resume_unwind(e);
}
}
}
#[derive(Debug)]
struct PortfolioStoppableScheduler<S> {
scheduler: S,
stop_signal: Arc<AtomicBool>,
}
impl<S: Scheduler> Scheduler for PortfolioStoppableScheduler<S> {
fn new_execution(&mut self) -> Option<Schedule> {
if self.stop_signal.load(Ordering::SeqCst) {
None
} else {
self.scheduler.new_execution()
}
}
fn next_task(
&mut self,
runnable_tasks: &[TaskId],
current_task: Option<TaskId>,
is_yielding: bool,
) -> Option<TaskId> {
if self.stop_signal.load(Ordering::SeqCst) {
None
} else {
self.scheduler.next_task(runnable_tasks, current_task, is_yielding)
}
}
fn next_u64(&mut self) -> u64 {
self.scheduler.next_u64()
}
}