summaryrefslogtreecommitdiffstats
path: root/plugins/plugin_httpstop/src/lib.rs
blob: c109f826433792fba5a1d214194557ff9e837c33 (plain)
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
use std::convert::Infallible;

use hyper::{Body, Request, Response, Server};
use tedge_api::{
    plugin::{HandleTypes, PluginExt},
    Address, CoreMessages, Plugin, PluginBuilder, PluginDirectory, PluginError,
};
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, Instrument};

#[derive(serde::Deserialize, Debug, tedge_api::Config)]
struct HttpStopConfig {
    /// The address to listen on
    bind: std::net::SocketAddr,
}

#[derive(Debug, miette::Diagnostic, thiserror::Error)]
enum Error {
    #[error("Failed to parse configuration")]
    ConfigParseFailed(#[from] toml::de::Error),

    #[error("HTTP Server stop failed")]
    FailedToStopMainloop(#[from] tokio::task::JoinError),
}

pub struct HttpStopPluginBuilder;

#[async_trait::async_trait]
impl<PD> PluginBuilder<PD> for HttpStopPluginBuilder
where
    PD: PluginDirectory,
{
    fn kind_name() -> &'static str
    where
        Self: Sized,
    {
        "httpstop"
    }

    fn kind_configuration() -> Option<tedge_api::ConfigDescription> {
        Some(<HttpStopConfig as tedge_api::AsConfig>::as_config())
    }

    fn kind_message_types() -> HandleTypes
    where
        Self: Sized,
    {
        HttpStopPlugin::get_handled_types()
    }

    async fn verify_configuration(
        &self,
        config: &tedge_api::PluginConfiguration,
    ) -> Result<(), tedge_api::PluginError> {
        debug!("Verifying HttpStopPlugin configuration");
        config
            .clone()
            .try_into::<HttpStopConfig>()
            .map(|_| ())
            .map_err(Error::from)
            .map_err(PluginError::from)
    }

    async fn instantiate(
        &self,
        config: tedge_api::PluginConfiguration,
        cancellation_token: tokio_util::sync::CancellationToken,
        plugin_dir: &PD,
    ) -> Result<tedge_api::plugin::BuiltPlugin, tedge_api::PluginError> {
        debug!("Instantiating HttpStopPlugin");
        let config = config
            .clone()
            .try_into::<HttpStopConfig>()
            .map_err(Error::from)?;

        let plugin = HttpStopPlugin {
            cancellation_token,
            bind: config.bind,
            core: plugin_dir.get_address_for_core(),

            join_handle: None,
        };

        Ok(plugin.finish())
    }
}

#[derive(Debug)]
pub struct HttpStopPlugin {
    cancellation_token: CancellationToken,
    bind: std::net::SocketAddr,
    core: Address<CoreMessages>,

    join_handle: Option<JoinHandle<Result<(), hyper::Error>>>,
}

impl tedge_api::plugin::PluginDeclaration for HttpStopPlugin {
    type HandledMessages = ();
}

#[async_trait::async_trait]
impl Plugin for HttpStopPlugin {
    #[tracing::instrument(name = "plugin.httpstop.start", skip(self))]
    async fn start(&mut self) -> Result<(), PluginError> {
        debug!("Setting up HttpStopPlugin");
        let addr = self.core.clone();
        let svc = hyper::service::make_service_fn(move |_conn| {
            let addr = addr.clone();
            let service = hyper::service::service_fn(move |req| request_handler(addr.clone(), req));

            async move { Ok::<_, Infallible>(service) }
        });

        let cancellation_token = self.cancellation_token.clone();
        let serv = Server::bind(&self.bind)
            .serve(svc)
            .with_graceful_shutdown(async move {
                cancellation_token.cancelled().await;
            });

        self.join_handle = Some(tokio::spawn(
            serv.instrument(tracing::debug_span!("plugin.httpstop.server")),
        ));
        Ok(())
    }

    #[tracing::instrument(name = "plugin.httpstop.shutdown", skip(self))]
    async fn shutdown(&mut self) -> Result<(), PluginError> {
        debug!("Shutting down HttpStopPlugin");
        if let Some(join_handle) = self.join_handle.take() {
            let _ = join_handle
                .instrument(tracing::debug_span!("plugin.httpstop.server.shutdown"))
                .await
                .map_err(Error::FailedToStopMainloop)?;
        }
        Ok(())
    }
}

#[tracing::instrument(name = "plugin.httpstop.server.request_handler")]
async fn request_handler(
    addr: Address<CoreMessages>,
    _: Request<Body>,
) -> Result<Response<Body>, Infallible> {
    debug!("Received request, stopping thin-edge now.");
    let _ = addr.send_and_wait(tedge_api::message::StopCore).await;
    Ok(Response::new("shutdown initiated".into()))
}