msr-core 0.3.7

Industrial Automation Toolbox - Common core components
Documentation
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
use std::{
    any::Any,
    sync::{
        atomic::{AtomicU8, Ordering},
        Arc, Condvar, Mutex,
    },
    thread::{self, JoinHandle},
};

use anyhow::Result;
use thread_priority::{ThreadId as NativeThreadId, ThreadPriority};

use super::{progress::ProgressHintReceiver, CompletionStatus, Worker};

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, num_derive::FromPrimitive)]
#[repr(u8)]
pub enum State {
    #[default]
    Initial,
    Starting,
    Running,
    Suspending,
    Finishing,
    Terminating,
}

impl State {
    #[must_use]
    pub const fn to_u8(self) -> u8 {
        self as u8
    }

    #[must_use]
    pub fn from_u8(value: u8) -> Option<Self> {
        num_traits::FromPrimitive::from_u8(value)
    }
}

/// Spawn parameters
///
/// The parameters are passed into the worker thread when spawned
/// and are recovered after joining the worker thread for later reuse.
///
/// If joining the work thread fails these parameters will be lost
/// inevitably!
#[allow(missing_debug_implementations)]
pub struct Context<W: Worker> {
    pub progress_hint_rx: ProgressHintReceiver,
    pub worker: W,
    pub environment: <W as Worker>::Environment,
}

#[derive(Debug)]
pub struct WorkerThread<W: Worker> {
    shared_state: Arc<SharedState>,
    join_handle: JoinHandle<TerminatedThread<W>>,
}

impl<W> WorkerThread<W>
where
    W: Worker,
{
    #[must_use]
    pub fn load_state(&self) -> State {
        self.shared_state.load_state()
    }

    #[allow(clippy::must_use_candidate)]
    pub fn wait_until_started(&self) -> State {
        self.shared_state
            .wait_until_state_condition(|state| match state {
                State::Initial | State::Starting => false,
                State::Running | State::Suspending | State::Finishing | State::Terminating => true,
            })
    }

    #[allow(clippy::must_use_candidate)]
    pub fn wait_until_not_running(&self) -> State {
        self.shared_state
            .wait_until_state_condition(|state| match state {
                State::Initial | State::Starting | State::Running => false,
                State::Suspending | State::Finishing | State::Terminating => true,
            })
    }
}

struct ThreadSchedulingScope {
    native_id: NativeThreadId,
    saved_priority: ThreadPriority,

    #[cfg(target_family = "unix")]
    saved_policy: thread_priority::ThreadSchedulePolicy,
}

// TODO: Prevent passing of instances to different threads
//#![feature(negative_impls)]
//impl !Send for ThreadSchedulingScope {}

impl ThreadSchedulingScope {
    #[cfg(not(target_family = "windows"))]
    fn enter() -> anyhow::Result<Self> {
        log::debug!("Entering real-time scope");
        let native_id = thread_priority::thread_native_id();
        let thread_id = thread::current().id();
        let saved_policy = thread_priority::thread_schedule_policy().map_err(|err| {
            anyhow::anyhow!(
                "Failed to save the thread scheduling policy of the current process: {:?}",
                err,
            )
        })?;
        let saved_priority = thread_priority::get_thread_priority(native_id).map_err(|err| {
            anyhow::anyhow!(
                "Failed to save the priority of thread {:?} ({:?}): {:?}",
                thread_id,
                native_id,
                err,
            )
        })?;
        let adjusted_priority = ThreadPriority::Max;
        if adjusted_priority != saved_priority {
            log::debug!(
                "Adjusting priority of thread {:?} ({:?}): {:?} -> {:?}",
                thread_id,
                native_id,
                saved_priority,
                adjusted_priority
            );
        }
        let adjusted_policy = thread_priority::ThreadSchedulePolicy::Realtime(
            // Non-preemptive scheduling (in contrast to RoundRobin)
            thread_priority::RealtimeThreadSchedulePolicy::Fifo,
        );
        if adjusted_policy != saved_policy {
            log::debug!(
                "Adjusting scheduling policy of thread {:?} ({:?}): {:?} -> {:?}",
                thread_id,
                native_id,
                saved_policy,
                adjusted_policy
            );
        }
        if let Err(err) = thread_priority::set_thread_priority_and_policy(
            native_id,
            adjusted_priority,
            adjusted_policy,
        ) {
            log::warn!(
                "Failed to adjust priority and scheduling policy of thread {:?} ({:?}): {:?}",
                thread_id,
                native_id,
                err
            );
            // Fallback: Only try to adjust the priority
            thread_priority::set_current_thread_priority(adjusted_priority).map_err(|err| {
                anyhow::anyhow!(
                    "Failed to adjust priority of thread {:?} ({:?}): {:?}",
                    thread_id,
                    native_id,
                    err
                )
            })?;
        }
        Ok(Self {
            native_id,
            saved_priority,
            saved_policy,
        })
    }

    #[cfg(target_family = "windows")]
    fn maximize_current_thread_priority() -> anyhow::Result<(NativeThreadId, ThreadPriority)> {
        let native_id = thread_priority::thread_native_id();
        let thread_id = thread::current().id();
        let saved_priority = thread_priority::get_thread_priority(native_id).map_err(|err| {
            anyhow::anyhow!(
                "Failed to save the priority of thread {:?} ({:?}): {:?}",
                thread_id,
                native_id,
                err,
            )
        })?;
        let adjusted_priority = ThreadPriority::Max;
        if adjusted_priority != saved_priority {
            log::debug!(
                "Adjusting priority of thread {:?} ({:?}): {:?} -> {:?}",
                thread_id,
                native_id,
                saved_priority,
                adjusted_priority
            );
        }
        thread_priority::set_current_thread_priority(adjusted_priority).map_err(|err| {
            anyhow::anyhow!(
                "Failed to adjust priority of thread {:?} ({:?}): {:?}",
                thread_id,
                native_id,
                err
            )
        })?;
        Ok((native_id, saved_priority))
    }

    #[cfg(target_family = "windows")]
    fn enter() -> anyhow::Result<Self> {
        log::debug!("Entering real-time scope");
        let (native_id, saved_priority) = Self::maximize_current_thread_priority()?;
        Ok(Self {
            native_id,
            saved_priority,
        })
    }
}

impl Drop for ThreadSchedulingScope {
    #[cfg(not(target_family = "windows"))]
    fn drop(&mut self) {
        log::debug!("Leaving real-time scope");
        assert_eq!(self.native_id, thread_priority::thread_native_id());
        if let Err(err) = thread_priority::set_thread_priority_and_policy(
            self.native_id,
            self.saved_priority,
            self.saved_policy,
        ) {
            log::error!(
                "Failed to restore priority and scheduling policy of thread {:?} ({:?}): {:?}",
                thread::current().id(),
                self.native_id,
                err
            );
        }
    }

    #[cfg(target_family = "windows")]
    fn drop(&mut self) {
        log::debug!("Leaving real-time scope");
        assert_eq!(self.native_id, thread_priority::thread_native_id());
        if let Err(err) = thread_priority::set_current_thread_priority(self.saved_priority) {
            log::error!(
                "Failed to restore priority of thread {:?} ({:?}): {:?}",
                thread::current().id(),
                self.native_id,
                err
            )
        }
    }
}

fn thread_fn<W>(
    context: &mut Context<W>,
    thread_scheduling: ThreadScheduling,
    shared_state: &SharedState,
) -> Result<()>
where
    W: Worker,
{
    let Context {
        progress_hint_rx,
        worker,
        environment,
    } = context;

    log::debug!("Starting");
    shared_state.store_state(State::Starting);
    worker.start_working(environment)?;
    log::debug!("Started");

    let scheduling_scope = match thread_scheduling {
        ThreadScheduling::Default => None,
        ThreadScheduling::Realtime => Some(ThreadSchedulingScope::enter()?),
        ThreadScheduling::RealtimeOrDefault => ThreadSchedulingScope::enter().ok(),
    };

    log::debug!("Running");
    shared_state.store_state(State::Running);

    loop {
        match worker.perform_work(environment, progress_hint_rx)? {
            CompletionStatus::Suspending => {
                // The worker may have decided to suspend itself independent
                // of the current progress hint.
                if !progress_hint_rx.try_suspending() {
                    // Suspending is not permitted
                    log::debug!("Suspending rejected");
                    continue;
                }
                log::debug!("Suspending");
                shared_state.store_state(State::Suspending);
                progress_hint_rx.wait_while_suspending();
                log::debug!("Resuming");
                shared_state.store_state(State::Running);
            }
            CompletionStatus::Finishing => {
                // The worker may have decided to finish itself independent
                // of the current progress hint.
                if !progress_hint_rx.try_finishing() {
                    // Suspending is not permitted
                    log::debug!("Finishing rejected");
                    continue;
                }
                // Leave custom scheduling scope before finishing
                drop(scheduling_scope);
                // Exit running loop
                break;
            }
        }
    }

    log::debug!("Finishing");
    shared_state.store_state(State::Finishing);
    worker.finish_working(environment)?;
    log::debug!("Finished");

    log::debug!("Terminating");
    shared_state.store_state(State::Terminating);

    Ok(())
}

/// Outcome of [`WorkerThread::join()`]
#[allow(missing_debug_implementations)]
pub struct TerminatedThread<W: Worker> {
    /// The result of the thread function
    pub result: Result<()>,

    /// The recovered parameters
    pub context: Context<W>,
}

/// Outcome of [`WorkerThread::join()`]
#[allow(missing_debug_implementations)]
pub enum JoinedThread<W: Worker> {
    Terminated(TerminatedThread<W>),
    JoinError(Box<dyn Any + Send + 'static>),
}

#[derive(Debug, Clone, Copy)]
pub enum ThreadScheduling {
    /// Default
    ///
    /// Do not modify the current thread's priority and leave the
    /// process's scheduling policy untouched.
    Default,

    /// Real-time
    ///
    /// Switch thread to real-time priority and try to switch to a real-time
    /// scheduling policy. The latter is optional and failures are only logged,
    /// not reported.
    Realtime,

    /// Real-time with fallback
    ///
    /// Try to apply a real-time strategy, but silently fall back `Default`
    /// if it fails. This is handy for tests in an environment that does not
    /// permit real-time scheduling, e.g. running the tests in containers
    /// on a CI platform.
    RealtimeOrDefault,
}

#[derive(Debug)]
struct SharedState {
    state: AtomicU8,
    notify_state_changed_mutex: Mutex<()>,
    notify_state_changed_condvar: Condvar,
}

impl SharedState {
    fn load_state(&self) -> State {
        State::from_u8(self.state.load(Ordering::Acquire)).unwrap()
    }

    fn store_state(&self, state: State) {
        let guard = self.notify_state_changed_mutex.lock();
        debug_assert!(guard.is_ok());
        self.state.store(state.to_u8(), Ordering::Release);
        drop(guard);
        self.notify_state_changed_condvar.notify_all();
    }

    fn wait_until_state_condition(&self, mut state_condition: impl FnMut(State) -> bool) -> State {
        // Try non-blocking first
        let state = self.load_state();
        if state_condition(state) {
            return state;
        }
        // Blocking
        let mut guard = self
            .notify_state_changed_mutex
            .lock()
            .expect("not poisoned");
        loop {
            let state = self.load_state();
            if state_condition(state) {
                return state;
            }
            guard = self
                .notify_state_changed_condvar
                .wait(guard)
                .expect("not poisoned");
        }
    }
}

impl Default for SharedState {
    fn default() -> Self {
        Self {
            state: State::default().to_u8().into(),
            notify_state_changed_mutex: Default::default(),
            notify_state_changed_condvar: Default::default(),
        }
    }
}

impl<W> WorkerThread<W>
where
    W: Worker + Send + 'static,
    <W as Worker>::Environment: Send + 'static,
{
    pub fn spawn(context: Context<W>, thread_scheduling: ThreadScheduling) -> Self {
        let shared_state = Arc::new(SharedState::default());
        let join_handle = {
            let shared_state = Arc::clone(&shared_state);
            std::thread::spawn({
                move || {
                    // The function parameters need to be mutable within the real-time thread
                    let mut context = context;
                    let result = thread_fn(&mut context, thread_scheduling, &shared_state);
                    let context = context;
                    TerminatedThread { result, context }
                }
            })
        };
        Self {
            shared_state,
            join_handle,
        }
    }

    pub fn join(self) -> JoinedThread<W> {
        let Self {
            join_handle,
            shared_state,
        } = self;
        log::debug!("Joining thread");
        let joined_thread = join_handle
            .join()
            .map_or_else(JoinedThread::JoinError, JoinedThread::Terminated);
        debug_assert_eq!(State::Terminating, shared_state.load_state());
        joined_thread
    }
}

#[cfg(test)]
mod tests;