fabaccess-bffh/src/initiator.rs

208 lines
6.4 KiB
Rust
Raw Normal View History

2021-09-30 10:07:42 +02:00
use std::sync::Arc;
2020-12-02 16:20:50 +01:00
use std::pin::Pin;
use std::task::{Poll, Context};
2020-12-01 10:21:39 +01:00
use std::future::Future;
use std::collections::HashMap;
2020-12-14 12:39:01 +01:00
2021-01-26 15:33:50 +01:00
use smol::Timer;
2020-12-01 09:44:18 +01:00
2020-12-14 12:39:01 +01:00
use slog::Logger;
2020-12-02 16:20:50 +01:00
use futures::future::BoxFuture;
2020-12-07 12:11:07 +01:00
use futures_signals::signal::{Signal, Mutable, MutableSignalCloned};
2020-12-02 16:20:50 +01:00
use crate::machine::{Machine, ReturnToken};
use crate::db::machine::MachineState;
2021-09-30 10:07:42 +02:00
use crate::db::user::{User, UserId, UserData, Internal as UserDB};
use crate::db::access::AccessControl;
2020-12-01 16:06:39 +01:00
use crate::network::InitMap;
2020-12-02 17:12:25 +01:00
2020-12-01 10:21:39 +01:00
use crate::error::Result;
2020-12-14 12:39:01 +01:00
use crate::config::Config;
2020-12-01 10:21:39 +01:00
2020-12-09 10:51:47 +01:00
pub trait Sensor {
2021-09-30 10:07:42 +02:00
fn run_sensor(&mut self) -> BoxFuture<'static, (Option<UserId>, MachineState)>;
2020-12-09 10:51:47 +01:00
}
type BoxSensor = Box<dyn Sensor + Send>;
pub struct Initiator {
2021-01-26 15:11:50 +01:00
log: Logger,
2020-12-02 16:20:50 +01:00
signal: MutableSignalCloned<Option<Machine>>,
machine: Option<Machine>,
2020-12-02 17:15:25 +01:00
future: Option<BoxFuture<'static, (Option<User>, MachineState)>>,
// TODO: Prepare the init for async state change requests.
state_change_fut: Option<BoxFuture<'static, Result<ReturnToken>>>,
2020-12-02 16:20:50 +01:00
token: Option<ReturnToken>,
sensor: BoxSensor,
2021-09-30 10:07:42 +02:00
userdb: UserDB,
access: AccessControl,
2020-12-01 10:21:39 +01:00
}
impl Initiator {
2021-09-30 10:07:42 +02:00
pub fn new(log: Logger, sensor: BoxSensor, signal: MutableSignalCloned<Option<Machine>>, userdb: UserDB, access: AccessControl) -> Self {
2020-12-02 16:20:50 +01:00
Self {
2021-01-26 15:11:50 +01:00
log: log,
2020-12-02 16:20:50 +01:00
signal: signal,
machine: None,
future: None,
state_change_fut: None,
2020-12-02 16:20:50 +01:00
token: None,
2020-12-02 17:12:25 +01:00
sensor: sensor,
2021-09-30 10:07:42 +02:00
userdb,
access,
2020-12-02 16:20:50 +01:00
}
}
2020-12-07 12:11:07 +01:00
2021-09-30 10:07:42 +02:00
pub fn wrap(log: Logger, sensor: BoxSensor, userdb: UserDB, access: Arc<AccessControl>) -> (Mutable<Option<Machine>>, Self) {
2020-12-07 12:11:07 +01:00
let m = Mutable::new(None);
let s = m.signal_cloned();
2021-09-30 10:07:42 +02:00
(m, Self::new(log, sensor, s, userdb, access))
2020-12-07 12:11:07 +01:00
}
2020-12-02 16:20:50 +01:00
}
impl Future for Initiator {
2020-12-02 16:20:50 +01:00
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let mut this = &mut *self;
// First of course, see what machine we should work with.
match Signal::poll_change(Pin::new(&mut this.signal), cx) {
Poll::Pending => { }
Poll::Ready(None) => return Poll::Ready(()),
// Keep in mind this is actually an Option<Machine>
2021-01-26 15:11:50 +01:00
Poll::Ready(Some(machine)) => {
match machine.as_ref().map(|m| m.try_lock()) {
None => info!(this.log, "Deinstalled machine"),
Some(None) => info!(this.log, "Installed new machine with locked mutex!"),
Some(Some(g)) => info!(this.log, "Installed new machine {}", g.id),
}
this.machine = machine;
},
2020-12-02 16:20:50 +01:00
}
// Do as much work as we can:
loop {
// Always poll the state change future first
if let Some(ref mut f) = this.state_change_fut {
match Future::poll(Pin::new(f), cx) {
// If there is a state change future and it would block we return early
Poll::Pending => {
2021-01-26 15:11:50 +01:00
debug!(this.log, "State change blocked");
return Poll::Pending;
},
Poll::Ready(Ok(tok)) => {
2021-01-26 15:11:50 +01:00
debug!(this.log, "State change returned ok");
// Explicity drop the future
let _ = this.state_change_fut.take();
// Store the given return token for future use
this.token.replace(tok);
}
Poll::Ready(Err(e)) => {
2021-01-26 15:11:50 +01:00
info!(this.log, "State change returned err: {}", e);
// Explicity drop the future
let _ = this.state_change_fut.take();
}
}
}
2020-12-02 16:20:50 +01:00
// If there is a future, poll it
match this.future.as_mut().map(|future| Future::poll(Pin::new(future), cx)) {
None => {
2020-12-02 17:15:25 +01:00
this.future = Some(this.sensor.run_sensor());
2020-12-02 16:20:50 +01:00
},
2021-09-30 10:07:42 +02:00
Some(Poll::Ready((uid, state))) => {
2021-01-26 15:11:50 +01:00
debug!(this.log, "Sensor returned a new state");
2020-12-02 16:20:50 +01:00
this.future.take();
let f = this.machine.as_mut().map(|machine| {
2021-09-30 10:07:42 +02:00
machine.request_state_change(state, this.access.clone(), user)
});
this.state_change_fut = f;
2020-12-02 16:20:50 +01:00
}
Some(Poll::Pending) => return Poll::Pending,
}
}
2020-12-01 10:21:39 +01:00
}
2020-12-01 09:44:18 +01:00
}
2021-09-30 10:07:42 +02:00
pub fn load(log: &Logger, config: &Config, userdb: UserDB, access: Arc<AccessControl>) -> Result<(InitMap, Vec<Initiator>)> {
let mut map = HashMap::new();
2020-12-14 12:39:01 +01:00
let initiators = config.initiators.iter()
2021-09-21 07:48:19 +02:00
.map(|(k,v)| (k, load_single(log, k, &v.module, &v.params)))
2020-12-14 12:39:01 +01:00
.filter_map(|(k,n)| match n {
None => None,
Some(i) => Some((k, i)),
});
let mut v = Vec::new();
for (name, initiator) in initiators {
2021-09-30 10:07:42 +02:00
let (m, i) = Initiator::wrap(log.new(o!("name" => name.clone())), initiator, userdb.clone(), access.clone());
2020-12-14 12:39:01 +01:00
map.insert(name.clone(), m);
v.push(i);
}
Ok((map, v))
}
fn load_single(
log: &Logger,
name: &String,
module_name: &String,
_params: &HashMap<String, String>
2020-12-14 12:39:01 +01:00
) -> Option<BoxSensor>
{
match module_name.as_ref() {
"Dummy" => {
Some(Box::new(Dummy::new(log)))
2020-12-14 12:39:01 +01:00
},
_ => {
error!(log, "No initiator found with name \"{}\", configured as \"{}\"",
module_name, name);
None
}
}
2020-12-01 09:44:18 +01:00
}
2020-12-02 17:12:25 +01:00
2020-12-02 17:15:25 +01:00
pub struct Dummy {
log: Logger,
step: bool,
2020-12-02 17:15:25 +01:00
}
2020-12-02 17:12:25 +01:00
2020-12-02 17:15:25 +01:00
impl Dummy {
pub fn new(log: &Logger) -> Self {
Self { log: log.new(o!("module" => "Dummy Initiator")), step: false }
2020-12-02 17:15:25 +01:00
}
}
2020-12-02 17:12:25 +01:00
2020-12-02 17:15:25 +01:00
impl Sensor for Dummy {
fn run_sensor(&mut self)
2021-09-30 10:07:42 +02:00
-> BoxFuture<'static, (Option<UserId>, MachineState)>
2020-12-02 17:12:25 +01:00
{
2020-12-02 17:15:25 +01:00
let step = self.step;
self.step = !step;
info!(self.log, "Kicking off new dummy initiator state change: {}", step);
2020-12-02 17:15:25 +01:00
2020-12-02 17:12:25 +01:00
let f = async move {
Timer::after(std::time::Duration::from_secs(1)).await;
if step {
2020-12-02 17:15:25 +01:00
return (None, MachineState::free());
2020-12-02 17:12:25 +01:00
} else {
2021-09-30 10:07:42 +02:00
let user = UserId::new("test".to_string(), None, None);
return (Some(user), MachineState::used(Some(user)));
2020-12-02 17:12:25 +01:00
}
};
Box::pin(f)
}
}