AnalyticsManager.cpp 22.6 KB
Newer Older
Alessio Netti's avatar
Alessio Netti committed
1
2
3
4
5
//
// Created by Netti, Alessio on 10.12.18.
//

#include "AnalyticsManager.h"
Alessio Netti's avatar
Alessio Netti committed
6
#include "timestamp.h"
Alessio Netti's avatar
Alessio Netti committed
7
8
9
10
11

void AnalyticsManager::clear() {
    for(const auto& p : _plugins)
        p.destroy(p.configurator);
    _plugins.clear();
Alessio Netti's avatar
Alessio Netti committed
12
    _status = CLEAR;
Alessio Netti's avatar
Alessio Netti committed
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
bool AnalyticsManager::probe(const string& path, const string& globalFile) {
    std::string cfgPath = path;
    boost::property_tree::iptree cfg;

    if (cfgPath != "" && cfgPath[cfgPath.length() - 1] != '/')
        cfgPath.append("/");

    try {
        boost::property_tree::read_info(cfgPath + globalFile, cfg);
    } catch (boost::property_tree::info_parser_error &e) {
        return false;
    }

    if(cfg.find("analyzerPlugins") == cfg.not_found()) 
        return false;

    int pluginCtr = 0;
    BOOST_FOREACH(boost::property_tree::iptree::value_type &plugin, cfg.get_child("analyzerPlugins")) {
        if (boost::iequals(plugin.first, "analyzerPlugin"))
            pluginCtr++;
    }

    if( pluginCtr == 0) 
        return false;
    else
        return true;
}

Alessio Netti's avatar
Alessio Netti committed
43
44
45
46
47
bool AnalyticsManager::load(const string& path, const string& globalFile, const pluginSettings_t& pluginSettings) {
    //The load code is pretty much the same as in Configuration.cpp to load pusher plugins
    _configPath = path;
    _pluginSettings = pluginSettings;
    boost::property_tree::iptree cfg;
48
49
50
51

    if (_configPath != "" && _configPath[_configPath.length()-1] != '/')
        _configPath.append("/");

Alessio Netti's avatar
Alessio Netti committed
52
    try {
53
        boost::property_tree::read_info(_configPath + globalFile, cfg);
Alessio Netti's avatar
Alessio Netti committed
54
    } catch (boost::property_tree::info_parser_error& e) {
Alessio Netti's avatar
Alessio Netti committed
55
        LOG(error) << "Error when reading analyzer plugins from " << globalFile << ": " << e.what();
Alessio Netti's avatar
Alessio Netti committed
56
57
58
        return false;
    }

Alessio Netti's avatar
Alessio Netti committed
59
60
    if(cfg.find("analyzerPlugins") == cfg.not_found()) {
        LOG(warning) << "No analyzerPlugins block found, skipping data analytics initialization!";
Alessio Netti's avatar
Alessio Netti committed
61
62
        _status = LOADED;
        return true;
Alessio Netti's avatar
Alessio Netti committed
63
64
    }

Alessio Netti's avatar
Alessio Netti committed
65
    //Reading plugins
Alessio Netti's avatar
Alessio Netti committed
66
67
68
69
70
71
72
73
74
75
76
77
78
    BOOST_FOREACH(boost::property_tree::iptree::value_type &plugin, cfg.get_child("analyzerPlugins")) {
        if (boost::iequals(plugin.first, "analyzerPlugin")) {
            if (!plugin.second.empty()) {
                LOG(info) << "Loading analyzer plugin \"" << plugin.second.data() << "\"...";
                std::string pluginConfig; //path to config file for plugin
                std::string pluginLib = "libdcdbanalyzer_" + plugin.second.data();
#if __APPLE__
                pluginLib+= ".dylib";
#else
                pluginLib+= ".so";
#endif
                BOOST_FOREACH(boost::property_tree::iptree::value_type &val, plugin.second) {
                    if (boost::iequals(val.first, "path")) {
79
                        std::string iPath = val.second.data();
Alessio Netti's avatar
Alessio Netti committed
80
                        // If path not specified we will look up in the default lib-directories (usr/lib and friends)
81
82
83
84
                        if (iPath != "") {
                            if (iPath[iPath.length()-1] != '/')
                                iPath.append("/");
                            pluginLib = iPath + pluginLib;
Alessio Netti's avatar
Alessio Netti committed
85
86
87
                        }
                    } else if (boost::iequals(val.first, "config")) {
                        pluginConfig = val.second.data();
Alessio Netti's avatar
Alessio Netti committed
88
                        // If config-path not specified we will look for pluginName.conf in the global conf directory
Alessio Netti's avatar
Alessio Netti committed
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
                        if (pluginConfig == "")
                            pluginConfig = _configPath + plugin.second.data() + ".conf";
                    } else {
                        LOG(warning) << "  Value \"" << val.first << "\" not recognized. Omitting";
                    }
                }
                // Open dl-code based on http://tldp.org/HOWTO/C++-dlopen/thesolution.html
                if (FILE *file = fopen(pluginConfig.c_str(), "r")) {
                    fclose(file);
                    an_dl_t dynLib;
                    dynLib.id = plugin.second.data();
                    dynLib.DL = NULL;
                    dynLib.configurator = NULL;

                    // If plugin.conf exists, open libdcdbanalyzer_pluginName.so and read config
                    LOG(info) << pluginConfig << " found";
                    dynLib.DL = dlopen(pluginLib.c_str(), RTLD_NOW);
                    if(!dynLib.DL) {
                        LOG(error) << "Cannot load " << dynLib.id << "-library: " << dlerror();
                        return false;
                    }
                    dlerror();

                    // Set dynLib an_dl_t struct, load create and destroy symbols
                    dynLib.create = (an_create_t*) dlsym(dynLib.DL, "create");
                    const char* dlsym_error = dlerror();
                    if (dlsym_error) {
                        LOG(error) << "Cannot load symbol create for " << dynLib.id << ": " << dlsym_error;
                        return false;
                    }

                    dynLib.destroy = (an_destroy_t*) dlsym(dynLib.DL, "destroy");
                    dlsym_error = dlerror();
                    if (dlsym_error) {
                        LOG(error) << "Cannot load symbol destroy for " << dynLib.id << ": " << dlsym_error;
                        return false;
                    }

                    dynLib.configurator = dynLib.create();
                    dynLib.configurator->setGlobalSettings(_pluginSettings);
                    // Read the analyzer plugin configuration
                    if (!(dynLib.configurator->readConfig(pluginConfig))) {
                        LOG(error) << "Plugin \"" << dynLib.id << "\" could not read configuration!";
                        return false;
                    }

                    // Returning an empty vector may indicate problems with the config file
                    if(dynLib.configurator->getAnalyzers().size() == 0) {
                        LOG(warning) << "Plugin \"" << dynLib.id << "\" created no analyzers!";
Alessio Netti's avatar
Alessio Netti committed
138
                    } else if(!checkTopics(dynLib)) {
Alessio Netti's avatar
Alessio Netti committed
139
                        LOG(error) << "Problematic MQTT topics or sensor names, please check your config files!";
Alessio Netti's avatar
Alessio Netti committed
140
                        return false;
Alessio Netti's avatar
Alessio Netti committed
141
142
143
144
145
146
147
148
149
150
                    }
                    //save dl-struct
                    _plugins.push_back(dynLib);
                    LOG(info) << "Plugin \"" << dynLib.id << "\" loaded!";
                } else {
                    LOG(info) << pluginConfig << " not found. Omitting";
                }
            }
        }
    }
Alessio Netti's avatar
Alessio Netti committed
151
    _status = LOADED;
Alessio Netti's avatar
Alessio Netti committed
152
153
154
155
    return true;
}

bool AnalyticsManager::init(boost::asio::io_service& io, const string& plugin) {
Alessio Netti's avatar
Alessio Netti committed
156
157
158
159
    if(_status != LOADED) {
        LOG(error) << "Cannot init, AnalyticsManager is not loaded!";
        return false;
    }
Alessio Netti's avatar
Alessio Netti committed
160
    bool out=false;
Alessio Netti's avatar
Alessio Netti committed
161
162
    for (const auto &p : _plugins)
        //Actions always affect either one or all plugins, and always all analyzers within said plugin
163
        if(plugin=="" || plugin==p.id) {
Alessio Netti's avatar
Alessio Netti committed
164
            out = true;
165
            LOG(info) << "Init \"" << p.id << "\" data analytics plugin";
Alessio Netti's avatar
Alessio Netti committed
166
167
            for (const auto &a : p.configurator->getAnalyzers())
                a->init(io);
168
        }
Alessio Netti's avatar
Alessio Netti committed
169
    return out;
Alessio Netti's avatar
Alessio Netti committed
170
171
172
}

bool AnalyticsManager::reload(boost::asio::io_service& io, const string& plugin) {
Alessio Netti's avatar
Alessio Netti committed
173
174
175
176
    if(_status != LOADED) {
        LOG(error) << "Cannot reload, AnalyticsManager is not loaded!";
        return false;
    }
Alessio Netti's avatar
Alessio Netti committed
177
    bool out=false;
Alessio Netti's avatar
Alessio Netti committed
178
179
    for (const auto &p : _plugins)
        if(plugin=="" || plugin==p.id) {
180
            LOG(info) << "Reload \"" << p.id << "\" data analytics plugin";
Alessio Netti's avatar
Alessio Netti committed
181
            out = true;
Alessio Netti's avatar
Alessio Netti committed
182
183
184
185
            //Removing obsolete MQTT topics
            removeTopics(p);
            //Reloading plugin
            if(!p.configurator->reReadConfig())
Alessio Netti's avatar
Alessio Netti committed
186
                return false;
Alessio Netti's avatar
Alessio Netti committed
187
188
189
190
191
192
193
194
            //Checking new MQTT topics
            if(!checkTopics(p)) {
                removeTopics(p);
                p.configurator->clearConfig();
                return false;
            } else
                for (const auto &a : p.configurator->getAnalyzers())
                    a->init(io);
Alessio Netti's avatar
Alessio Netti committed
195
        }
Alessio Netti's avatar
Alessio Netti committed
196
    return out;
Alessio Netti's avatar
Alessio Netti committed
197
198
}

Alessio Netti's avatar
Alessio Netti committed
199
200
void AnalyticsManager::removeTopics(an_dl_t p) {
    MQTTChecker& mqttCheck = MQTTChecker::getInstance();
Alessio Netti's avatar
Alessio Netti committed
201
    for(const auto& a : p.configurator->getAnalyzers()) {
Alessio Netti's avatar
Alessio Netti committed
202
        mqttCheck.removeGroup(a->getName());
Alessio Netti's avatar
Alessio Netti committed
203
204
        if (a->getStreaming())
            for (const auto &u : a->getUnits())
Alessio Netti's avatar
Alessio Netti committed
205
                for (const auto &o: u->getBaseOutputs()) {
Alessio Netti's avatar
Alessio Netti committed
206
                    mqttCheck.removeTopic(o->getMqtt());
Alessio Netti's avatar
Alessio Netti committed
207
208
                    mqttCheck.removeName(o->getName());
                }
Alessio Netti's avatar
Alessio Netti committed
209
    }
Alessio Netti's avatar
Alessio Netti committed
210
211
212
213
214
}

bool AnalyticsManager::checkTopics(an_dl_t p) {
    MQTTChecker& mqttCheck = MQTTChecker::getInstance();
    bool validTopics=true;
Alessio Netti's avatar
Alessio Netti committed
215
    for(const auto& a : p.configurator->getAnalyzers()) {
Alessio Netti's avatar
Alessio Netti committed
216
        if (!mqttCheck.checkGroup(a->getName()))
Alessio Netti's avatar
Alessio Netti committed
217
218
219
220
            validTopics = false;
        if (a->getStreaming())
            for (const auto &u : a->getUnits())
                for (const auto &o: u->getBaseOutputs())
Alessio Netti's avatar
Alessio Netti committed
221
                    if (!mqttCheck.checkTopic(o->getMqtt()) || !mqttCheck.checkName(o->getName()))
Alessio Netti's avatar
Alessio Netti committed
222
                        validTopics = false;
Alessio Netti's avatar
Alessio Netti committed
223
    }
Alessio Netti's avatar
Alessio Netti committed
224
225
226
    return validTopics;
}

Alessio Netti's avatar
Alessio Netti committed
227
bool AnalyticsManager::start(const string& plugin, const string& analyzer) {
Alessio Netti's avatar
Alessio Netti committed
228
229
230
231
    if(_status != LOADED) {
        LOG(error) << "Cannot start, AnalyticsManager is not loaded!";
        return false;
    }
Alessio Netti's avatar
Alessio Netti committed
232
    bool out=false;
Alessio Netti's avatar
Alessio Netti committed
233
    for (const auto &p : _plugins)
234
235
        if(plugin=="" || plugin==p.id) {
            LOG(info) << "Start \"" << p.id << "\" data analytics plugin";
Alessio Netti's avatar
Alessio Netti committed
236
            for (const auto &a : p.configurator->getAnalyzers())
Alessio Netti's avatar
Alessio Netti committed
237
238
239
240
241
                // Only streaming analyzers can be started
                if(a->getStreaming() && (analyzer=="" || analyzer==a->getName())) {
                    a->start();
                    out=true;
                }
242
        }
Alessio Netti's avatar
Alessio Netti committed
243
    return out;
Alessio Netti's avatar
Alessio Netti committed
244
245
}

Alessio Netti's avatar
Alessio Netti committed
246
bool AnalyticsManager::stop(const string& plugin, const string& analyzer) {
Alessio Netti's avatar
Alessio Netti committed
247
248
249
250
    if(_status != LOADED) {
        LOG(error) << "Cannot stop, AnalyticsManager is not loaded!";
        return false;
    }
Alessio Netti's avatar
Alessio Netti committed
251
    bool out=false;
Alessio Netti's avatar
Alessio Netti committed
252
    for (const auto &p : _plugins)
253
254
        if(plugin=="" || plugin==p.id) {
            LOG(info) << "Stop \"" << p.id << "\" data analytics plugin";
Alessio Netti's avatar
Alessio Netti committed
255
            for (const auto &a : p.configurator->getAnalyzers())
Alessio Netti's avatar
Alessio Netti committed
256
257
258
259
260
                // Only streaming analyzers can be stopped
                if(a->getStreaming() && (analyzer=="" || analyzer==a->getName())) {
                    a->stop();
                    out=true;
                }
261
        }
Alessio Netti's avatar
Alessio Netti committed
262
    return out;
Alessio Netti's avatar
Alessio Netti committed
263
264
}

Alessio Netti's avatar
Alessio Netti committed
265
restResponse_t AnalyticsManager::REST(const vector<string>& pathStrs, const vector<pair<string,string>>& queries, const string& method, boost::asio::io_service& io) {
Alessio Netti's avatar
Alessio Netti committed
266
267
268
269
270
271
272
273
274
275
276
    // Some preliminary checks
    if(_status != LOADED)
        throw runtime_error("Cannot forward REST command, AnalyticsManager is not loaded!");
    if (method != "GET" && method != "PUT")
        throw invalid_argument("Unsupported REST method!");
    if(pathStrs.size() < 2 || pathStrs[0] != "analytics")
        throw invalid_argument("Received malformed request!");

    // Determining if JSON output was requested
    bool json = false;
    for (auto& p : queries)
Alessio Netti's avatar
Alessio Netti committed
277
278
        if (p.first == "json")
            json = stoi(p.second) > 0;
Alessio Netti's avatar
Alessio Netti committed
279

Alessio Netti's avatar
Alessio Netti committed
280
    restResponse_t reply;
Alessio Netti's avatar
Alessio Netti committed
281
282
283
284
285
286
    std::ostringstream data;

    // GET block of commands
    if (method == "GET") {
        // Help cheatsheet command
        if (pathStrs[1] == "help") {
Alessio Netti's avatar
Alessio Netti committed
287
            reply.response = restCheatSheet;
Alessio Netti's avatar
Alessio Netti committed
288
289
290
291
292
293
294
        // Command to list data analytics plugins
        } else if (pathStrs[1] == "plugins") {
            if (json) {
                boost::property_tree::ptree root, plugins;
                for(auto& p : _plugins)
                    plugins.put(p.id, "");
                root.add_child("plugins", plugins);
Alessio Netti's avatar
Alessio Netti committed
295
                boost::property_tree::write_json(data, root, true);
Alessio Netti's avatar
Alessio Netti committed
296
297
298
            } else
                for(auto& p : _plugins)
                    data << p.id << "\n";
Alessio Netti's avatar
Alessio Netti committed
299
            reply.data = data.str();
Alessio Netti's avatar
Alessio Netti committed
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
        // Managing commands that have a path length greater than 2
        } else {
            if (pathStrs.size() < 3)
                throw invalid_argument("Received malformed request, no second path part!");

            string analyzer = pathStrs.size() > 3 ? pathStrs[2] : "";
            string action = pathStrs[pathStrs.size() - 1];
            string plugin = pathStrs[1];

            // Listing all sensors in one or all analyzers of a plugin; the [analyzer] block is optional
            if (action == "sensors") {
                bool found = false;
                for (auto &p : _plugins) {
                    if (p.id == plugin) {
                        if (json) {
                            boost::property_tree::ptree root, sensors;

                            // In JSON mode, sensors are arranged hierarchically by plugin->analyzer->sensor
                            for (auto &a : p.configurator->getAnalyzers())
                                if (a->getStreaming() && (analyzer == "" || analyzer == a->getName())) {
                                    found = true;
                                    boost::property_tree::ptree group;
                                    for (auto &u : a->getUnits())
                                        for (auto &s : u->getBaseOutputs())
                                            // Explicitly adding nodes to the ptree as to prevent BOOST from performing
                                            // parsing on the node names
Alessio Netti's avatar
Alessio Netti committed
326
                                            group.push_back(boost::property_tree::ptree::value_type("", boost::property_tree::ptree(s->getMqtt())));
Alessio Netti's avatar
Alessio Netti committed
327
328
329
                                    sensors.add_child(a->getName(), group);
                                }
                            root.add_child(p.id, sensors);
Alessio Netti's avatar
Alessio Netti committed
330
                            boost::property_tree::write_json(data, root, true);
Alessio Netti's avatar
Alessio Netti committed
331
332
333
334
335
336
                        } else {
                            for (auto &a : p.configurator->getAnalyzers())
                                if (a->getStreaming() && (analyzer == "" || analyzer == a->getName())) {
                                    found = true;
                                    for (auto &u : a->getUnits())
                                        for (auto &s : u->getBaseOutputs())
Alessio Netti's avatar
Alessio Netti committed
337
                                            data << a->getName() << "::" << s->getMqtt() << "\n";
Alessio Netti's avatar
Alessio Netti committed
338
339
                                }
                        }
Alessio Netti's avatar
Alessio Netti committed
340
                        reply.data = data.str();
Alessio Netti's avatar
Alessio Netti committed
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
                        break;
                    }
                }
                if (!found)
                    throw domain_error("Plugin or analyzer not found!");
            } else if (action == "units") {
                bool found = false;
                for (auto &p : _plugins) {
                    if (p.id == plugin) {
                        if (json) {
                            boost::property_tree::ptree root, units;

                            // In JSON mode, units are arranged hierarchically by plugin->analyzer->unit
                            for (auto &a : p.configurator->getAnalyzers())
                                if (a->getStreaming() && (analyzer == "" || analyzer == a->getName())) {
                                    found = true;
                                    boost::property_tree::ptree group;
                                    for (auto &u : a->getUnits())
Alessio Netti's avatar
Alessio Netti committed
359
                                        group.push_back(boost::property_tree::ptree::value_type("", boost::property_tree::ptree(u->getName())));
Alessio Netti's avatar
Alessio Netti committed
360
361
362
                                    units.add_child(a->getName(), group);
                                }
                            root.add_child(p.id, units);
Alessio Netti's avatar
Alessio Netti committed
363
                            boost::property_tree::write_json(data, root, true);
Alessio Netti's avatar
Alessio Netti committed
364
365
366
367
368
                        } else {
                            for (auto &a : p.configurator->getAnalyzers())
                                if (a->getStreaming() && (analyzer == "" || analyzer == a->getName())) {
                                    found = true;
                                    for (auto &u : a->getUnits())
Alessio Netti's avatar
Alessio Netti committed
369
                                        data << a->getName() << "::" << u->getName() << "\n";
Alessio Netti's avatar
Alessio Netti committed
370
371
                                }
                        }
Alessio Netti's avatar
Alessio Netti committed
372
                        reply.data = data.str();
Alessio Netti's avatar
Alessio Netti committed
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
                        break;
                    }
                }
                if (!found)
                    throw domain_error("Plugin or analyzer not found!");
            } else if (action == "analyzers") {
                if(analyzer != "")
                    throw invalid_argument("Analyzers GET command does not support analyzer names!");
                bool found = false;
                for (auto &p : _plugins) {
                    if (p.id == plugin) {
                        if (json) {
                            boost::property_tree::ptree root, analyzers;

                            // For each analyzer, we output its type as well
                            for (auto &a : p.configurator->getAnalyzers())
                                analyzers.push_back(boost::property_tree::ptree::value_type(a->getName(), boost::property_tree::ptree(a->getStreaming() ? "streaming" : "on-demand")));
                            root.add_child(p.id, analyzers);
Alessio Netti's avatar
Alessio Netti committed
391
                            boost::property_tree::write_json(data, root, true);
Alessio Netti's avatar
Alessio Netti committed
392
393
394
395
396
                        } else {
                            for (auto &a : p.configurator->getAnalyzers())
                                data << a->getName() << " " << (a->getStreaming() ? "streaming\n" : "on-demand\n");
                        }
                        found = true;
Alessio Netti's avatar
Alessio Netti committed
397
                        reply.data = data.str();
Alessio Netti's avatar
Alessio Netti committed
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
                        break;
                    }
                }
                if (!found)
                    throw domain_error("Plugin not found!");
            } else
                throw invalid_argument("Unknown action " + action + " requested");
        }
    // PUT block of commands
    } else if (method == "PUT") {

        if (pathStrs.size() < 3)
            throw invalid_argument("Received malformed request, no second path part!");

        string analyzer = pathStrs.size() > 3 ? pathStrs[2] : "";
        string action = pathStrs[pathStrs.size() - 1];
        string plugin = pathStrs[1];

        // Managing generic plugin PUT actions
        if (action == "start") {
            if( start(plugin, analyzer) ) {
Alessio Netti's avatar
Alessio Netti committed
419
                reply.response = "Plugin " + plugin + " " + analyzer + ": Sensors started";
Alessio Netti's avatar
Alessio Netti committed
420
421
422
423
            } else
                throw domain_error("Plugin or analyzer not found!");
        } else if (action == "stop") {
            if( stop(plugin, analyzer) ) {
Alessio Netti's avatar
Alessio Netti committed
424
                reply.response = "Plugin " + plugin + " " + analyzer + ": Sensors stopped";
Alessio Netti's avatar
Alessio Netti committed
425
426
427
428
            } else
                throw domain_error("Plugin or analyzer not found!");
        } else if (action == "reload") {
            if(!reload(io, plugin))
Alessio Netti's avatar
Alessio Netti committed
429
                throw domain_error("Plugin not found or reload failed, please check the config files and MQTT topics!");
Alessio Netti's avatar
Alessio Netti committed
430
431
            else if(!start(plugin))
                throw runtime_error("Plugin cannot be restarted!");
Alessio Netti's avatar
Alessio Netti committed
432
            reply.response = "Plugin " + plugin + ": Sensors reloaded";
Alessio Netti's avatar
Alessio Netti committed
433
434
435
436
        } else if (action == "compute") {
            if(pathStrs.size() < 4)
                throw invalid_argument("Received malformed request, no third path part!");

437
            string unit = SensorNavigator::rootKey;
Alessio Netti's avatar
Alessio Netti committed
438
439
            for (auto& p : queries)
                if (p.first == "unit")
Alessio Netti's avatar
Alessio Netti committed
440
                    unit = MQTTChecker::convertTopic(p.second);
Alessio Netti's avatar
Alessio Netti committed
441

442
            bool found=false, unitFound=false;
Alessio Netti's avatar
Alessio Netti committed
443
444
445
446
447
            for (auto &p : _plugins)
                if (p.id == plugin)
                    for (auto &a : p.configurator->getAnalyzers())
                        if( a->getName() == analyzer ) {
                            found = true;
448
449
450
451
452
453
454
455
456
457
458
459
460
                            map <string, reading_t> outMap;
                            try {
                                outMap = a->computeOnDemand(unit);
                                unitFound = true;
                            } catch(const domain_error& e) {
                                // In the particular case where an analyzer is duplicated, it could be that the right
                                // unit is found only after a few tries. Therefore, we handle the domain_error
                                // exception raised in AnalyzerTemplate, and allow the search to continue
                                if(a->getStreaming() && a->getDuplicate())
                                    continue;
                                else
                                    throw;
                            }
Alessio Netti's avatar
Alessio Netti committed
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
                            if (json) {
                                boost::property_tree::ptree root, outputs;
                                // Iterating through the outputs of the on-demand computation and adding them to a JSON
                                for (const auto& kv : outMap) {
                                    boost::property_tree::ptree sensor;
                                    sensor.push_back(boost::property_tree::ptree::value_type("timestamp", boost::property_tree::ptree(to_string(kv.second.timestamp))));
                                    sensor.push_back(boost::property_tree::ptree::value_type("value", boost::property_tree::ptree(to_string(kv.second.value))));
                                    outputs.push_back(boost::property_tree::ptree::value_type(kv.first, sensor));
                                }
                                root.add_child(a->getName(), outputs);
                                boost::property_tree::write_json(data, root, true);
                            } else {
                                for (const auto& kv : outMap)
                                    data << kv.first << " ts: " << kv.second.timestamp << " v: " << kv.second.value << "\n";
                            }
                            reply.data = data.str();
                            break;
                        }
            if(!found)
                throw domain_error("Plugin or analyzer not found!");
481
482
483
            // This if branch is accessed only if the target analyzer is streaming and duplicated
            else if(!unitFound)
                throw domain_error("Node " + unit + " does not belong to the domain of " + analyzer + "!");
Alessio Netti's avatar
Alessio Netti committed
484
485
486
487
488
489
490
491
492
        } else {
            // Managing custom REST PUT actions defined at the analyzer level
            bool found = false;
            for (auto &p : _plugins)
                if (p.id == plugin)
                    for (auto &a : p.configurator->getAnalyzers())
                        if (analyzer == "" || analyzer == a->getName()) {
                            found = true;
                            // Any thrown exception is catched outside in the HTTPserver
Alessio Netti's avatar
Alessio Netti committed
493
                            reply = a->REST(action, queries);
Alessio Netti's avatar
Alessio Netti committed
494
495
496
497
                        }
            if (!found)
                throw domain_error("Plugin or analyzer not found!");
        }
Alessio Netti's avatar
Alessio Netti committed
498
    }
Alessio Netti's avatar
Alessio Netti committed
499
    return reply;
Alessio Netti's avatar
Alessio Netti committed
500
}