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
use prometheus::IntGauge;
use std::error::Error;
use std::fmt::{self, Debug, Display, Formatter};
use std::io;
use std::sync::{Arc, Mutex};
use std::thread::{self, Builder, JoinHandle};
use futures::channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
use futures::stream::StreamExt;
use tokio::task::LocalSet;
use super::metrics::*;
pub struct Stopped<T>(pub T);
impl<T> Display for Stopped<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "channel has been closed")
}
}
impl<T> Debug for Stopped<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "channel has been closed")
}
}
impl<T> From<Stopped<T>> for Box<dyn Error + Sync + Send + 'static> {
fn from(_: Stopped<T>) -> Box<dyn Error + Sync + Send + 'static> {
box_err!("channel has been closed")
}
}
pub trait Runnable<T: Display> {
fn run(&mut self, t: T);
fn shutdown(&mut self) {}
}
pub struct Scheduler<T> {
name: Arc<str>,
sender: UnboundedSender<Option<T>>,
metrics_pending_task_count: IntGauge,
}
pub fn dummy_scheduler<T: Display>() -> Scheduler<T> {
let (tx, _) = unbounded();
Scheduler::new("dummy future scheduler".to_owned(), tx)
}
impl<T: Display> Scheduler<T> {
pub fn new<S: Into<Arc<str>>>(name: S, sender: UnboundedSender<Option<T>>) -> Scheduler<T> {
let name = name.into();
Scheduler {
metrics_pending_task_count: WORKER_PENDING_TASK_VEC.with_label_values(&[&name]),
name,
sender,
}
}
pub fn schedule(&self, task: T) -> Result<(), Stopped<T>> {
debug!("scheduling task {}", task);
if let Err(err) = self.sender.unbounded_send(Some(task)) {
return Err(Stopped(err.into_inner().unwrap()));
}
self.metrics_pending_task_count.inc();
Ok(())
}
}
impl<T: Display> Clone for Scheduler<T> {
fn clone(&self) -> Scheduler<T> {
Scheduler {
name: Arc::clone(&self.name),
sender: self.sender.clone(),
metrics_pending_task_count: self.metrics_pending_task_count.clone(),
}
}
}
pub struct Worker<T: Display> {
scheduler: Scheduler<T>,
receiver: Mutex<Option<UnboundedReceiver<Option<T>>>>,
handle: Option<JoinHandle<()>>,
}
fn poll<R, T>(mut runner: R, mut rx: UnboundedReceiver<Option<T>>)
where
R: Runnable<T> + Send + 'static,
T: Display + Send + 'static,
{
tikv_alloc::add_thread_memory_accessor();
let current_thread = thread::current();
let name = current_thread.name().unwrap();
let metrics_pending_task_count = WORKER_PENDING_TASK_VEC.with_label_values(&[name]);
let metrics_handled_task_count = WORKER_HANDLED_TASK_VEC.with_label_values(&[name]);
let handle = LocalSet::new();
{
let task = async {
while let Some(msg) = rx.next().await {
if let Some(t) = msg {
runner.run(t);
metrics_pending_task_count.dec();
metrics_handled_task_count.inc();
} else {
break;
}
}
};
tokio::runtime::Builder::new()
.basic_scheduler()
.build()
.unwrap()
.block_on(handle.run_until(task));
}
runner.shutdown();
tikv_alloc::remove_thread_memory_accessor();
}
impl<T: Display + Send + 'static> Worker<T> {
pub fn new<S: Into<Arc<str>>>(name: S) -> Worker<T> {
let (tx, rx) = unbounded();
Worker {
scheduler: Scheduler::new(name, tx),
receiver: Mutex::new(Some(rx)),
handle: None,
}
}
pub fn start<R>(&mut self, runner: R) -> Result<(), io::Error>
where
R: Runnable<T> + Send + 'static,
{
let mut receiver = self.receiver.lock().unwrap();
info!("starting working thread"; "worker" => &self.scheduler.name);
if receiver.is_none() {
warn!("worker has been started"; "worker" => &self.scheduler.name);
return Ok(());
}
let rx = receiver.take().unwrap();
let h = Builder::new()
.name(thd_name!(self.scheduler.name.as_ref()))
.spawn(move || poll(runner, rx))?;
self.handle = Some(h);
Ok(())
}
pub fn scheduler(&self) -> Scheduler<T> {
self.scheduler.clone()
}
pub fn schedule(&self, task: T) -> Result<(), Stopped<T>> {
self.scheduler.schedule(task)
}
pub fn is_busy(&self) -> bool {
self.handle.is_none()
}
pub fn name(&self) -> &str {
&self.scheduler.name
}
pub fn stop(&mut self) -> Option<thread::JoinHandle<()>> {
info!("stoping worker"; "worker" => &self.scheduler.name);
let handle = self.handle.take()?;
if let Err(e) = self.scheduler.sender.unbounded_send(None) {
warn!("failed to stop worker thread"; "err" => ?e);
}
Some(handle)
}
}
#[cfg(test)]
mod tests {
use std::sync::mpsc::{self, Sender};
use std::time::Duration;
use std::time::Instant;
use crate::timer::GLOBAL_TIMER_HANDLE;
use futures::compat::Future01CompatExt;
use tokio::task::spawn_local;
use tokio_timer::timer;
use super::*;
struct StepRunner {
timer: timer::Handle,
ch: Sender<u64>,
}
impl Runnable<u64> for StepRunner {
fn run(&mut self, step: u64) {
self.ch.send(step).unwrap();
let f = self
.timer
.delay(Instant::now() + Duration::from_millis(step))
.compat();
spawn_local(f);
}
fn shutdown(&mut self) {
self.ch.send(0).unwrap();
}
}
#[test]
fn test_future_worker() {
let mut worker = Worker::new("test-async-worker");
let (tx, rx) = mpsc::channel();
worker
.start(StepRunner {
timer: GLOBAL_TIMER_HANDLE.clone(),
ch: tx,
})
.unwrap();
assert!(!worker.is_busy());
let start = Instant::now();
worker.schedule(500).unwrap();
worker.schedule(1000).unwrap();
worker.schedule(1500).unwrap();
assert_eq!(rx.recv_timeout(Duration::from_secs(3)).unwrap(), 500);
assert_eq!(rx.recv_timeout(Duration::from_secs(3)).unwrap(), 1000);
assert_eq!(rx.recv_timeout(Duration::from_secs(3)).unwrap(), 1500);
assert!(start.elapsed() < Duration::from_secs(2));
worker.stop().unwrap().join().unwrap();
assert!(worker.is_busy());
assert_eq!(0, rx.recv().unwrap());
}
#[test]
fn test_block_on_inside_worker() {
struct BlockingRunner;
impl Runnable<bool> for BlockingRunner {
fn run(&mut self, _: bool) {
futures::executor::block_on(async {});
}
}
let mut worker = Worker::new("test-block-on-worker");
worker.start(BlockingRunner).unwrap();
worker.schedule(true).unwrap();
worker.schedule(false).unwrap();
worker.stop().unwrap().join().unwrap();
}
}