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
mod control_command;
mod monitor;

pub(crate) use self::control_command::{ControlCommand, Reply};
pub use self::{control_command::WatchdogQuery, monitor::WatchdogMonitor};
use crate::{
    runtime::Runtimes,
    service::{ServiceError, ServiceIdentifier, StatusReport},
};
use async_trait::async_trait;
use std::{any::Any, fmt};
use thiserror::Error;
use tokio::sync::{mpsc, oneshot};

/// trait to define the different core services and their
/// associated metadata
#[async_trait]
pub trait Organix: Send + Sync {
    fn new(_: &mut Runtimes) -> Self;

    fn stop(&mut self, service_identifier: ServiceIdentifier) -> Result<(), WatchdogError>;
    async fn status(
        &mut self,
        service_identifier: ServiceIdentifier,
    ) -> Result<StatusReport, WatchdogError>;
    fn start(
        &mut self,
        service_identifier: ServiceIdentifier,
        watchdog_query: WatchdogQuery,
    ) -> Result<(), WatchdogError>;
    fn intercoms(
        &mut self,
        service_identifier: ServiceIdentifier,
    ) -> Result<Box<dyn Any + Send + 'static>, WatchdogError>;
}

pub struct Watchdog<T: Organix> {
    services: T,
    on_drop_send: oneshot::Sender<()>,
}

pub struct WatchdogBuilder<T>
where
    T: Organix,
{
    _marker: std::marker::PhantomData<T>,
}

#[derive(Debug, Error, PartialEq, Eq)]
pub enum WatchdogError {
    #[error("Unknown service {service_identifier}, available services are {possible_values:?}")]
    UnknownService {
        service_identifier: ServiceIdentifier,
        possible_values: &'static [ServiceIdentifier],
    },

    #[error("Cannot start service {service_identifier}: {source}")]
    CannotStartService {
        service_identifier: ServiceIdentifier,
        source: ServiceError,
    },

    #[error("Cannot connect to service {service_identifier}, service might be shutdown")]
    CannotConnectToService {
        service_identifier: ServiceIdentifier,
        retry_attempted: bool,
    },

    #[error("The watchdog didn't reply to the {context}: {reason}")]
    NoReply {
        reason: oneshot::error::RecvError,
        context: &'static str,
    },
}

impl<T> WatchdogBuilder<T>
where
    T: Organix,
{
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        Self {
            _marker: std::marker::PhantomData,
        }
    }

    pub fn build(self) -> WatchdogMonitor
    where
        T: Organix + 'static,
    {
        let mut runtimes = Runtimes::new().unwrap();

        let services = T::new(&mut runtimes);

        let (sender, receiver) = mpsc::channel(10);
        let (on_drop_send, on_drop_receive) = oneshot::channel();

        let watchdog = Watchdog {
            on_drop_send,
            services,
        };

        let watchdog_query_handle = runtimes.watchdog().handle().clone();

        let query = WatchdogQuery::new(watchdog_query_handle, sender.clone());

        runtimes
            .watchdog()
            .handle()
            .spawn(async move { watchdog.watchdog(receiver, query).await });

        WatchdogMonitor::new(runtimes, sender, on_drop_receive)
    }
}

impl<T> Watchdog<T>
where
    T: Organix,
{
    #[tracing::instrument(skip(self, cc, watchdog_query), target = "watchdog", level = "info")]
    async fn watchdog(
        mut self,
        mut cc: mpsc::Receiver<ControlCommand>,
        watchdog_query: WatchdogQuery,
    ) {
        while let Some(command) = cc.recv().await {
            match command {
                ControlCommand::Shutdown | ControlCommand::Kill => {
                    // TODO: for now we assume shutdown and kill are the same
                    //       but on the long run it will need to send a Shutdown
                    //       signal to every services so they can save state and
                    //       release resources properly

                    tracing::warn!(%command, "stopping watchdog");
                    break;
                }
                ControlCommand::Status {
                    service_identifier,
                    reply,
                } => {
                    let status_report = self.services.status(service_identifier).await;
                    if let Ok(status_report) = &status_report {
                        tracing::info!(
                            %status_report.identifier,
                            status_report.number_restart = status_report.started,
                            %status_report.status,
                            %status_report.intercom.number_sent,
                            %status_report.intercom.number_received,
                            %status_report.intercom.number_connections,
                            %status_report.intercom.processing_speed_mean,
                            %status_report.intercom.processing_speed_variance,
                            %status_report.intercom.processing_speed_standard_derivation,
                        );
                    }
                    reply.reply(status_report);
                }
                ControlCommand::Start {
                    service_identifier,
                    reply,
                } => {
                    tracing::info!(%service_identifier, "start");
                    reply.reply(
                        self.services
                            .start(service_identifier, watchdog_query.clone()),
                    );
                }
                ControlCommand::Stop {
                    service_identifier,
                    reply,
                } => {
                    tracing::info!(%service_identifier, "stop");
                    reply.reply(self.services.stop(service_identifier));
                }
                ControlCommand::Intercom {
                    service_identifier,
                    reply,
                } => {
                    tracing::trace!(%service_identifier, "query intercom");
                    // TODO: surround the operation with a timeout and
                    //       result to success
                    reply.reply(self.services.intercoms(service_identifier));
                }
            }
        }

        if self.on_drop_send.send(()).is_err() {
            // ignore error for now
        }
    }
}

impl<T: Organix> fmt::Debug for Watchdog<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Watchdog").finish()
    }
}