summaryrefslogtreecommitdiffstats
path: root/tedge/src/main.rs
blob: 8fc62dacb0ad279c3c91eebb9f23ebce2e147020 (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
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
use std::collections::HashSet;

use clap::Parser;
use miette::IntoDiagnostic;

use tedge_api::PluginBuilder;
use tedge_core::configuration::TedgeConfiguration;
use tedge_core::TedgeApplication;
use tedge_core::TedgeApplicationCancelSender;
use tedge_lib::measurement::Measurement;
use tracing::debug;
use tracing::error;
use tracing::info;

mod cli;
mod logging;

#[tokio::main]
#[tracing::instrument]
async fn main() -> miette::Result<()> {
    #[cfg(feature = "core_debugging")]
    {
        console_subscriber::init();
    }
    let args = crate::cli::Cli::parse();
    crate::logging::setup_logging(args.verbose, args.debug)?;
    info!("Tedge booting...");
    debug!("Tedge CLI: {:?}", args);
    let config = match args.command {
        cli::CliCommand::Run { ref config } => config,
        cli::CliCommand::ValidateConfig { ref config } => config,
    };

    let configuration = tokio::fs::read_to_string(config).await.into_diagnostic()?;

    let config: TedgeConfiguration = toml::de::from_str(&configuration).into_diagnostic()?;
    info!("Configuration loaded.");

    let application = TedgeApplication::builder();
    let mut plugin_kinds = HashSet::new();
    info!("Building application");

    macro_rules! register_plugin {
        ($app:ident, $cfg:tt, $pluginbuilder:ty, $pbinstance:expr) => {{
            cfg_if::cfg_if! {
                if #[cfg(feature = $cfg)] {
                    let kind_name: &'static str = <$pluginbuilder as PluginBuilder<tedge_core::PluginDirectory>>::kind_name();
                    info!("Registering plugin builder for plugins of type {}", kind_name);
                    if !plugin_kinds.insert(kind_name) {
                        miette::bail!("Plugin kind '{}' was already registered, cannot register!", kind_name)
                    }
                    $app.with_plugin_builder($pbinstance)?
                } else {
                    tracing::trace!("Not supporting plugins of type {}", std::stringify!($pluginbuilder));
                    $app
                }
            }
        }}
    }

    let application = {
        cfg_table::cfg_table! {
            [not(feature = "mqtt")] => register_plugin!(
                application,
                "builtin_plugin_log",
                plugin_log::LogPluginBuilder<(Measurement,)>,
                plugin_log::LogPluginBuilder::<(Measurement,)>::new()
            ),

            [feature = "mqtt"] => register_plugin!(
                application,
                "builtin_plugin_log",
                plugin_log::LogPluginBuilder<(Measurement, plugin_mqtt::IncomingMessage)>,
                plugin_log::LogPluginBuilder::<(Measurement, plugin_mqtt::IncomingMessage)>::new()
            ),
        }
    };

    let application = register_plugin!(
        application,
        "builtin_plugin_avg",
        plugin_avg::AvgPluginBuilder,
        plugin_avg::AvgPluginBuilder
    );
    let application = register_plugin!(
        application,
        "builtin_plugin_sysstat",
        plugin_sysstat::SysStatPluginBuilder,
        plugin_sysstat::SysStatPluginBuilder
    );
    let application = register_plugin!(
        application,
        "builtin_plugin_inotify",
        plugin_inotify::InotifyPluginBuilder,
        plugin_inotify::InotifyPluginBuilder
    );
    let application = register_plugin!(
        application,
        "builtin_plugin_httpstop",
        plugin_httpstop::HttpStopPluginBuilder,
        plugin_httpstop::HttpStopPluginBuilder
    );
    let application = register_plugin!(
        application,
        "builtin_plugin_measurement_filter",
        plugin_measurement_filter::MeasurementFilterPluginBuilder,
        plugin_measurement_filter::MeasurementFilterPluginBuilder
    );
    let application = register_plugin!(
        application,
        "builtin_plugin_azure_bridge",
        plugin_azure_bridge::AzureBridgeBuilder,
        plugin_azure_bridge::AzureBridgeBuilder
    );
    let application = register_plugin!(
        application,
        "mqtt",
        plugin_mqtt::MqttPluginBuilder,
        plugin_mqtt::MqttPluginBuilder::new()
    );
    let application = register_plugin!(
        application,
        "mqtt",
        plugin_mqtt_measurement_bridge::MqttMeasurementBridgePluginBuilder,
        plugin_mqtt_measurement_bridge::MqttMeasurementBridgePluginBuilder::new()
    );

    let application = register_plugin!(
        application,
        "builtin_plugin_random_measurements",
        plugin_random_measurements::RandomMeasurementsPluginBuilder,
        plugin_random_measurements::RandomMeasurementsPluginBuilder
    );

    let application = register_plugin!(
        application,
        "moneo",
        plugin_moneo_mapper::MoneoMapperPluginBuilder,
        plugin_moneo_mapper::MoneoMapperPluginBuilder
    );

    let (cancel_sender, application) = application.with_config(config)?;
    info!("Application built");

    match args.command {
        cli::CliCommand::Run { .. } => {
            debug!("Going to run the application");
            run(cancel_sender, application).await
        }
        cli::CliCommand::ValidateConfig { .. } => {
            debug!("Only going to validate the configuration");
            validate_config(&application).await?;
            info!("Configuration validated");
            Ok(())
        }
    }
}

async fn run(
    cancel_sender: TedgeApplicationCancelSender,
    application: TedgeApplication,
) -> miette::Result<()> {
    info!("Booting app now.");
    let mut run_fut = Box::pin(application.run());

    let kill_app = |fut| -> miette::Result<()> {
        error!("Killing application");
        drop(fut);
        miette::bail!("Application killed")
    };

    let res = tokio::select! {
        res = &mut run_fut => {
            res.into_diagnostic()
        },

        _int = tokio::signal::ctrl_c() => {
            if !cancel_sender.is_cancelled() {
                info!("Shutting down...");
                cancel_sender.cancel_app();
                tokio::select! {
                    res = &mut run_fut => res.into_diagnostic(),
                    _ = tokio::signal::ctrl_c() => kill_app(run_fut),
                }
            } else {
                kill_app(run_fut)
            }
        },
    };

    info!("Bye");
    res
}

async fn validate_config(application: &TedgeApplication) -> miette::Result<()> {
    let mut any_err = false;
    for (plugin_name, res) in application.verify_configurations().await {
        match res {
            Err(e) => {
                error!("Error in Plugin '{}' configuration: {:?}", plugin_name, e);
                any_err = true;
            }
            Ok(_) => {
                info!("Plugin '{}' configured correctly", plugin_name);
            }
        }
    }

    if any_err {
        Err(miette::miette!("Plugin configuration error"))
    } else {
        Ok(())
    }
}