AnalyzerConfiguratorTemplate.h 26.2 KB
Newer Older
Alessio Netti's avatar
Alessio Netti committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//
// Created by Netti, Alessio on 10.12.18.
//

#ifndef PROJECT_ANALYZERCONFIGURATORTEMPLATE_H
#define PROJECT_ANALYZERCONFIGURATORTEMPLATE_H

#include <map>
#include <set>

#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/info_parser.hpp>
#include "AnalyzerTemplate.h"
#include "AnalyzerConfiguratorInterface.h"
17
#include "sensorbase.h"
Alessio Netti's avatar
Alessio Netti committed
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

#include <iostream>
#include <sstream>
#include <iomanip>

#define CFG_VAL	boost::property_tree::iptree&

/**
 * Template that implements a standard AnalyzerConfiguratorInterface.
 *
 * Users should employ this template whenever possible, and create their own configurators only when strictly
 * necessary.
 */
template <class Analyzer, class SBase = SensorBase>
class AnalyzerConfiguratorTemplate : public AnalyzerConfiguratorInterface {

    // Verifying the types of input classes
    static_assert(std::is_base_of<SensorBase, SBase>::value, "SBase must derive from SensorBase!");
    static_assert(std::is_base_of<AnalyzerInterface, Analyzer>::value, "Analyzer must derive from AnalyzerInterface!");

protected:

    // For readability
    using A_Ptr = std::shared_ptr<Analyzer>;

    // Some wildcard characters
    const char COMMA = ',';
    const char OPEN_SQBRKET = '[';
    const char CLOSE_SQBRKET = ']';
    const char DASH = '-';

    // Keywords used to identify input and output sensor blocks
    const string INPUT_BLOCK = "input";
    const string OUTPUT_BLOCK = "output";
52
53
54
    const string ALL_CLAUSE = "all";
    const string ALL_REC_CLAUSE = "all-recursive";

Alessio Netti's avatar
Alessio Netti committed
55
56
    const std::string SENSOR_PATTERN = "(?i)<sensor>";
    const std::string GROUP_PATTERN = "(?i)<group>";
Alessio Netti's avatar
Alessio Netti committed
57
58
59
60
61
62
63

public:

    /**
    * @brief            Class constructor
    */
    AnalyzerConfiguratorTemplate() :
64
            _queryEngine(QueryEngine::getInstance()),
Alessio Netti's avatar
Alessio Netti committed
65
66
67
68
            _analyzerName("INVALID"),
            _baseName("INVALID"),
            _cfgPath(""),
            _mqttPrefix(""),
Alessio Netti's avatar
Alessio Netti committed
69
            _sensorPattern(""),
Alessio Netti's avatar
Alessio Netti committed
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
            _cacheInterval(900000) {}

    /**
    * @brief            Copy constructor is not available
    */
    AnalyzerConfiguratorTemplate(const AnalyzerConfiguratorTemplate&) = delete;

    /**
    * @brief            Assignment operator is not available
    */
    AnalyzerConfiguratorTemplate& operator=(const AnalyzerConfiguratorTemplate&) = delete;

    /**
    * @brief            Class destructor
    */
    virtual ~AnalyzerConfiguratorTemplate() {
        for (auto ta : _templateAnalyzers)
            delete ta.second;
Alessio Netti's avatar
Alessio Netti committed
88
89
        for (auto ts : _templateSensors)
            delete ts.second;
Alessio Netti's avatar
Alessio Netti committed
90
        _templateAnalyzers.clear();
Alessio Netti's avatar
Alessio Netti committed
91
92
        _templateSensors.clear();
        _templateProtoInputs.clear();
Alessio Netti's avatar
Alessio Netti committed
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
        _analyzerInterfaces.clear();
        _analyzers.clear();
    }

    /**
    * @brief                    Sets default global settings for analyzers
    *
    *                           This method should be called once after constructing a configurator and before reading
    *                           the configuration, so that it has access to the default global settings (which can
    *                           be overridden.
    *
    * @param pluginSettings	    struct with global default settings for the plugins.
    */
    virtual void setGlobalSettings(const pluginSettings_t& pluginSettings) final {
        _mqttPrefix = pluginSettings.mqttPrefix;
Alessio Netti's avatar
Alessio Netti committed
108
        _sensorPattern = pluginSettings.sensorPattern;
Alessio Netti's avatar
Alessio Netti committed
109
110
111
        _cacheInterval = pluginSettings.cacheInterval;
    }

112
113
114
115
116
117
118
    /**
    * @brief                    Print configuration as read in.
    *
    * @param ll                 Logging level to log with
    */
    void printConfig(LOG_LEVEL ll) final {
        LOG_VAR(ll) << "    General: ";
Michael Ott's avatar
Michael Ott committed
119
120
        LOG_VAR(ll) << "          MQTT-Prefix:    " << (_mqttPrefix != "" ? _mqttPrefix : std::string("DEFAULT"));
        LOG_VAR(ll) << "          Sensor Pattern: " << (_sensorPattern != "" ? _sensorPattern : std::string("DEFAULT"));
121
122
123
124
125
126
127
128
129
130
131
132
        LOG_VAR(ll) << "          Cache interval: " << _cacheInterval << " ms";

        //prints plugin specific configurator attributes and entities if present
        printConfiguratorConfig(ll);

        LOG_VAR(ll) << "    Analyzers: ";
        for(auto a : _analyzers) {
            LOG_VAR(ll) << "        Analyzer: " << a->getName();
            a->printConfig(ll);
        }
    }

Alessio Netti's avatar
Alessio Netti committed
133
134
135
136
137
138
139
140
141
142
143
144
    /**
    * @brief            Read a config file and instantiate analyzers accordingly
    *
    *                   This method supplies standard algorithms to instantiate analyzers and parse units from config
    *                   files accordingly. It should be overridden only if strictly necessary, which generally should
    *                   not happen.
    *
    * @param cfgPath    Path to the config file
    * @return	        True if successful, false otherwise
    */
    bool readConfig(std::string cfgPath) {
        _cfgPath = cfgPath;
Alessio Netti's avatar
Alessio Netti committed
145
        _unitGen.setNavigator(_queryEngine.getNavigator());
Alessio Netti's avatar
Alessio Netti committed
146
147
148
149
150
151
152
153
154
155
156
157
158
159

        boost::property_tree::iptree cfg;
        boost::property_tree::read_info(cfgPath, cfg);

        // Read global variables (if present overwrite those from global.conf)
        readGlobal(cfg);

        // Reading analyzers and template analyzers
        BOOST_FOREACH(boost::property_tree::iptree::value_type &val, cfg) {
            // In this block templates are parsed and read
            if (boost::iequals(val.first, "template_" + _analyzerName)) {
                LOG(debug) << "Template " << _analyzerName << " \"" << val.second.data() << "\"";
                if (!val.second.empty()) {
                    Analyzer* an = new Analyzer(val.second.data());
160
                    an->setTemplate(true);
Alessio Netti's avatar
Alessio Netti committed
161
                    if (!readAnalyzer(*an, val.second)) {
Alessio Netti's avatar
Alessio Netti committed
162
163
164
165
                        LOG(warning) << "Template " << _analyzerName << " \"" << val.second.data() << "\" has bad values! Ignoring...";
                        delete an;
                    }
                }
Alessio Netti's avatar
Alessio Netti committed
166
167
168
169
170
171
172
173
174
175
176
            // Sensor templates are read
            } else if (boost::iequals(val.first, "template_" + _baseName)) {
                LOG(debug) << "Template " << _baseName << " \"" << val.second.data() << "\"";
                if (!val.second.empty()) {
                    SBase* base = new SBase(val.second.data());
                    if (!readSensorBase(*base, val.second, true)) {
                        LOG(warning) << "Template " << _baseName << " \"" << val.second.data() << "\" has bad values! Ignoring...";
                        delete base;
                    }
                }
            // Here we read and instantiate analyzers
Alessio Netti's avatar
Alessio Netti committed
177
178
179
180
181
182
183
184
185
186
187
188
            } else if (boost::iequals(val.first, _analyzerName)) {
                LOG(debug) << _analyzerName << " \"" << val.second.data() << "\"";
                if (!val.second.empty()) {
                    A_Ptr an = std::make_shared<Analyzer>(val.second.data());
                    if (readAnalyzer(*an, val.second)) {
                        // If the analyzer must be duplicated for each compute unit, we copy-construct identical
                        // instances that have different unit IDs
                        unsigned numUnits = an->getUnits().size();
                        if(an->getDuplicate() && numUnits>1) {
                            for(unsigned int i=0; i < numUnits; i++) {
                                A_Ptr anCopy = std::make_shared<Analyzer>(*an);
                                anCopy->setUnitID(i);
189
                                anCopy->collapseUnits();
Alessio Netti's avatar
Alessio Netti committed
190
191
192
193
194
195
196
197
                                storeAnalyzer(anCopy);
                            }
                        } else
                            storeAnalyzer(an);
                    } else {
                        LOG(warning) << _analyzerName << " \"" << val.second.data() << "\" has bad values! Ignoring...";
                    }
                }
198
199
200
            } else if( !boost::iequals(val.first, "global") ) {
                LOG(error) << "\"" << val.first << "\": unknown construct!";
                return false;
Alessio Netti's avatar
Alessio Netti committed
201
202
203
204
205
206
            }
        }
        return true;
    }

    /**
Alessio Netti's avatar
Alessio Netti committed
207
    * @brief            Clears the plugin configuration
Alessio Netti's avatar
Alessio Netti committed
208
    *
Alessio Netti's avatar
Alessio Netti committed
209
210
    *                   This will stop any analyzers that have been created, destroy them and return the plugin to
    *                   its uninitialized state.
Alessio Netti's avatar
Alessio Netti committed
211
212
    *
    */
Alessio Netti's avatar
Alessio Netti committed
213
    void clearConfig() final {
Alessio Netti's avatar
Alessio Netti committed
214
215
216
217
218
219
220
221
        // Stop all analyzers
        for(auto a : _analyzers)
            a->stop();

        // Wait for all analyzers to finish
        for(auto a : _analyzers)
            a->wait();

Alessio Netti's avatar
Alessio Netti committed
222
        // First of all, delete all template analyzers and sensors
Alessio Netti's avatar
Alessio Netti committed
223
224
        for (auto ta : _templateAnalyzers)
            delete ta.second;
Alessio Netti's avatar
Alessio Netti committed
225
226
        for (auto ts : _templateSensors)
            delete ts.second;
Alessio Netti's avatar
Alessio Netti committed
227
228
229
230
231

        // Clear all analyzers
        _analyzerInterfaces.clear();
        _analyzers.clear();
        _templateAnalyzers.clear();
Alessio Netti's avatar
Alessio Netti committed
232
233
        _templateSensors.clear();
        _templateProtoInputs.clear();
Alessio Netti's avatar
Alessio Netti committed
234
235
236
237
238
239
240
241
242
243
244
245
    }

    /**
    * @brief            Clear all instantiated analyzers and read the configuration again
    *
    *                   This will stop any analyzers that have been created, destroy them and finally create new ones
    *                   from a new configuration read pass.
    *
    * @return	        True if successful, false otherwise
    */
    bool reReadConfig() final {
        clearConfig();
Alessio Netti's avatar
Alessio Netti committed
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281

        // Reading the configuration once again
        return readConfig(_cfgPath);
    }

    /**
    * @brief                   Return all instantiated analyzers
    *
    * @return	               Vector containing pointers to all analyzer interfaces of this plugin
    */
    std::vector<AnalyzerPtr>& getAnalyzers() final {
        return _analyzerInterfaces;
    }

protected:

    /**
    * @brief           Reads any derived analyzer attributes
    *
    *                  Pure virtual interface method, responsible for reading plugin-specific analyzer attributes.
    *
    * @param an		   The analyzer for which derived attributes must be set
    * @param config	   A Boost property (sub-)tree containing the config attributes
    */
    virtual void analyzer(Analyzer& an, CFG_VAL config) = 0;

    /**
    * @brief           Reads any derived sensor attributes
    *
    *                  Pure virtual interface method, responsible for reading plugin-specific sensor attributes.
    *
    * @param s		   The sensor for which derived attributes must be set
    * @param config	   A Boost property (sub-)tree containing the config attributes
    */
    virtual void sensorBase(SBase& s, CFG_VAL config) = 0;

282
283
284
285
286
287
    /**
    * @brief           Performs additional checks on instantiated units
    *
    *                  Pure virtual interface method, responsible for performing user-specified checks on units.
    *
    * @param u		   The unit that has been created
Alessio Netti's avatar
Alessio Netti committed
288
    * @return          True if the unit is valid, False otherwise
289
    */
Alessio Netti's avatar
Alessio Netti committed
290
    virtual bool unit(UnitTemplate<SBase>& u) = 0;
291

Alessio Netti's avatar
Alessio Netti committed
292
293
294
295
296
297
298
299
300
    /**
    * @brief           Reads additional global attributes on top of the default ones
    *
    *                  Virtual interface method, responsible for reading plugin-specific global attributes.
    *
    * @param config	   A Boost property (sub-)tree containing the global values
    */
    virtual void global(CFG_VAL config) {}

301
302
303
304
305
306
307
308
    /**
    * @brief            Print information about configurable configurator attributes.
    *
    *                   This method is virtual and can be overridden on a per-plugin basis.
    *
    * @param ll         Severity level to log with
    */
    virtual void printConfiguratorConfig(LOG_LEVEL ll) {
Alessio Netti's avatar
Alessio Netti committed
309
        LOG_VAR(ll) << "          No other plugin-specific general parameters defined";
310
    }
Alessio Netti's avatar
Alessio Netti committed
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334

    /**
    * @brief                   Store an analyzer in the internal vectors
    *
    * @param an                Shared pointer to a AnalyzerInterface object
    */
    void storeAnalyzer(A_Ptr an) {
        _analyzers.push_back(an);
        _analyzerInterfaces.push_back(an);
    }

    /**
    * @brief                   Reads a single analyzer configuration block
    *
    *                          Non-virtual interface method for class-internal use only. This will configure an
    *                          Analyzer object, and instantiate all units associated to it. All derived attributes
    *                          and additional configuration must be performed in the analyzer() virtual method.
    *
    * @param an	               The analyzer that must be configured
    * @param config	           A boost property (sub-)tree containing the analyzer values
    * @return	               True if successful, false otherwise
    */
    bool readAnalyzer(Analyzer& an, CFG_VAL config) {
        // Vectors containing "prototype" inputs and outputs to be modified with the actual compute units
Alessio Netti's avatar
Alessio Netti committed
335
        std::vector<shared_ptr<SBase>> protoInputs, protoOutputs;
336
        inputMode_t inputMode = SELECTIVE;
Alessio Netti's avatar
Alessio Netti committed
337
338
339
340
341
342
343
344
        // Check for the existence of a template definition to initialize the analyzer
        boost::optional<boost::property_tree::iptree&> def = config.get_child_optional("default");
        if(def) {
            LOG(debug) << "  Using \"" << def.get().data() << "\" as default.";
            auto it = _templateAnalyzers.find(def.get().data());
            if(it != _templateAnalyzers.end()) {
                an = *(it->second);
                an.setName(config.data());
345
                an.setTemplate(false);
Alessio Netti's avatar
Alessio Netti committed
346
347
                // Analyzers instantiated from templates DO NOT share the same units and output sensors. 
                // This would lead to too much naming ambiguity and is generally just not needed
Alessio Netti's avatar
Alessio Netti committed
348
                an.clearUnits();
Alessio Netti's avatar
Alessio Netti committed
349
350
351
                // The input sensors defined in the template are on the other hand preserved; this is meant as a 
                // workaround to shorten certain configurations 
                protoInputs = _templateProtoInputs[def.get().data()];
Alessio Netti's avatar
Alessio Netti committed
352
353
354
355
356
357
358
359
360
361
362
363
364
365
            } else {
                LOG(warning) << "Template " << _analyzerName << "\"" << def.get().data() << "\" not found! Using standard values.";
            }
        }
        // Reading attributes associated to AnalyzerInterface
        BOOST_FOREACH(boost::property_tree::iptree::value_type &val, config)
        {
            if (boost::iequals(val.first, "interval")) {
                an.setInterval(stoull(val.second.data()));
            } else if (boost::iequals(val.first, "minValues")) {
                an.setMinValues(stoull(val.second.data()));
            } else if (boost::iequals(val.first, "mqttPart")) {
                an.setMqttPart(val.second.data());
            } else if (boost::iequals(val.first, "sync")) {
Alessio Netti's avatar
Alessio Netti committed
366
                an.setSync(to_bool(val.second.data()));
Alessio Netti's avatar
Alessio Netti committed
367
368
            } else if (boost::iequals(val.first, "delay")) {
                an.setDelayInterval(stoull(val.second.data()) / 1000);
Alessio Netti's avatar
Alessio Netti committed
369
            } else if (boost::iequals(val.first, "duplicate")) {
Alessio Netti's avatar
Alessio Netti committed
370
                an.setDuplicate(to_bool(val.second.data()));
Alessio Netti's avatar
Alessio Netti committed
371
            } else if (boost::iequals(val.first, "streaming")) {
Alessio Netti's avatar
Alessio Netti committed
372
                an.setStreaming(to_bool(val.second.data()));
Alessio Netti's avatar
Alessio Netti committed
373
374
            } else if (boost::iequals(val.first, INPUT_BLOCK) || boost::iequals(val.first, OUTPUT_BLOCK)) {
                // Instantiating all sensors contained within the "input" or "output" block
375
                BOOST_FOREACH(boost::property_tree::iptree::value_type &valInner, val.second)
Alessio Netti's avatar
Alessio Netti committed
376
377
                {
                    if (boost::iequals(valInner.first, _baseName)) {
378
379
                        LOG(debug) << "    I/O " << _baseName << " " << valInner.second.data();
                        SBase sensor = SBase(valInner.second.data());
Alessio Netti's avatar
Alessio Netti committed
380
                        if (readSensorBase(sensor, valInner.second, false)) {
Alessio Netti's avatar
Alessio Netti committed
381
382
                            shared_ptr<SBase> sensorPtr = make_shared<SBase>(sensor);
                            val.first==INPUT_BLOCK ? protoInputs.push_back(sensorPtr) : protoOutputs.push_back(sensorPtr);
Alessio Netti's avatar
Alessio Netti committed
383
384
385
                        } else {
                            LOG(warning) << "I/O " << _baseName << " " << an.getName() << "::" << sensor.getName() << " could not be read! Omitting";
                        }
386
387
388
389
390
391
392
                        // An "all" or "all-recursive" statement in the input block causes all sensors related to the specific
                        // unit to be picked
                    } else if (boost::iequals(val.first, INPUT_BLOCK) && (boost::iequals(valInner.first, ALL_CLAUSE) || boost::iequals(valInner.first, ALL_REC_CLAUSE))) {
                        inputMode = boost::iequals(valInner.first, ALL_CLAUSE) ? ALL : ALL_RECURSIVE;
                    } else {
                        LOG(error) << "\"" << valInner.first << "\": unknown I/O construct!";
                        return false;
Alessio Netti's avatar
Alessio Netti committed
393
394
395
396
397
398
399
400
                    }
                }
            }
        }

        // Reading all derived attributes, if any
        analyzer(an, config);

Alessio Netti's avatar
Alessio Netti committed
401
402
        // Instantiating units and returning the result
        if(!an.getTemplate()) {
Alessio Netti's avatar
Alessio Netti committed
403
            vector <shared_ptr<UnitTemplate<SBase>>> *units = NULL;
Alessio Netti's avatar
Alessio Netti committed
404
            try {
Alessio Netti's avatar
Alessio Netti committed
405
                units = _unitGen.generateUnits(protoInputs, protoOutputs, inputMode, _mqttPrefix + an.getMqttPart(), !an.getStreaming());
Alessio Netti's avatar
Alessio Netti committed
406
407
            }
            catch (const std::exception &e) {
Alessio Netti's avatar
Alessio Netti committed
408
409
                LOG(error) << _analyzerName << " " << an.getName() << ": Error when creating units: " << e.what();
                delete units;
Alessio Netti's avatar
Alessio Netti committed
410
411
412
413
                return false;
            }

            for (auto &u: *units) {
Alessio Netti's avatar
Alessio Netti committed
414
415
416
417
418
                if(!constructSensorNames(*u, an)) {
                    an.clearUnits();
                    delete units;
                    return false;
                }
Alessio Netti's avatar
Alessio Netti committed
419
420
                if (an.getStreaming()) {
                    if (!unit(*u)) {
421
                        LOG(error) << "    Unit " << u->getName() << " did not pass the final check!";
Alessio Netti's avatar
Alessio Netti committed
422
423
424
                        an.clearUnits();
                        delete units;
                        return false;
425
426
                    } else {
                        LOG(debug) << "    Unit " << u->getName() << " generated.";
Alessio Netti's avatar
Alessio Netti committed
427
                        an.addUnit(u);
428
                    }
Alessio Netti's avatar
Alessio Netti committed
429
430
                } else {
                    if (unit(*u)) {
Alessio Netti's avatar
Alessio Netti committed
431
                        an.addToOndemandCache(u);
432
                        LOG(debug) << "    Template unit for on-demand operation " + u->getName() + " generated.";
Alessio Netti's avatar
Alessio Netti committed
433
434
435
436
437
438
439
                    } else {
                        LOG(error) << "    Template unit " << u->getName() << " did not pass the final check!";
                        an.clearUnits();
                        delete units;
                        return false;
                    }
                }
Alessio Netti's avatar
Alessio Netti committed
440
            }
Alessio Netti's avatar
Alessio Netti committed
441
            delete units;
Alessio Netti's avatar
Alessio Netti committed
442
443
444
445
446
447
448
449
        } else {
            // If the analyzer is a template, we add it to the related map
            auto ret = _templateAnalyzers.insert(std::pair<std::string, Analyzer*>(an.getName(), &an));
            if(!ret.second) {
                LOG(warning) << "Template " << _analyzerName << " " << an.getName() << " already exists! Omitting...";
                return false;
            }
            _templateProtoInputs.insert(std::pair<std::string, std::vector<shared_ptr<SBase>>>(an.getName(), protoInputs));
Alessio Netti's avatar
Alessio Netti committed
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
        }
        return true;
    }

    /**
    * @brief                   Reads a single sensor configuration block
    *
    *                          Non-virtual interface method for class-internal use only. This will configure a
    *                          sensor object. All derived attributes and additional configuration must be performed
    *                          in the sensorBase() virtual method.
    *
    * @param sBase	           The sensor that must be configured
    * @param config	           A boost property (sub-)tree containing the sensor values
    * @return	               True if successful, false otherwise
    */
Alessio Netti's avatar
Alessio Netti committed
465
    bool readSensorBase(SBase& sBase, CFG_VAL config, bool isTemplate=false) {
Alessio Netti's avatar
Alessio Netti committed
466
        sBase.setCacheInterval(_cacheInterval);
Alessio Netti's avatar
Alessio Netti committed
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
        if (!isTemplate) {
            // Copying parameters from the template (if defined)
            boost::optional<boost::property_tree::iptree&> def = config.get_child_optional("default");
            if(def) {
                LOG(debug) << "  Using \"" << def.get().data() << "\" as default.";
                auto it = _templateSensors.find(def.get().data());
                if(it != _templateSensors.end()) {
                    sBase = *(it->second);
                    sBase.setName(config.data());
                } else {
                    LOG(warning) << "Template " << _baseName << "\" " << def.get().data() << "\" not found! Using standard values.";
                }
            }
        }
        // Reading other sensor parameters
Alessio Netti's avatar
Alessio Netti committed
482
483
484
        BOOST_FOREACH(boost::property_tree::iptree::value_type &val, config) {
            if (boost::iequals(val.first, "mqttsuffix")) {
                sBase.setMqtt(val.second.data());
485
            } else if (boost::iequals(val.first, "skipConstVal")) {
Alessio Netti's avatar
Alessio Netti committed
486
                sBase.setSkipConstVal(to_bool(val.second.data()));
487
            } else if (boost::iequals(val.first, "delta")) {
Alessio Netti's avatar
Alessio Netti committed
488
                sBase.setDelta(to_bool(val.second.data()));
489
            } else if (boost::iequals(val.first, "sink")) {
Alessio Netti's avatar
Alessio Netti committed
490
                sBase.setSinkPath(val.second.data());
491
            } else if (boost::iequals(val.first, "subSampling")) {
Alessio Netti's avatar
Alessio Netti committed
492
                sBase.setSubsampling(std::stoul(val.second.data()));
Alessio Netti's avatar
Alessio Netti committed
493
494
495
            }
        }
        sensorBase(sBase, config);
Alessio Netti's avatar
Alessio Netti committed
496
497
498
499
500
501
502
503
504
        
        if(isTemplate) {
            auto ret = _templateSensors.insert(std::pair<std::string, SBase*>(sBase.getName(), &sBase));
            if(!ret.second) {
                LOG(warning) << "Template " << _baseName << " " << sBase.getName() << " already exists! Omitting...";
                return false;
            }
        }
        
Alessio Netti's avatar
Alessio Netti committed
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
        return true;
    }

    /**
    * @brief                   Reads the global configuration block
    *
    *                          Non-virtual interface method for class-internal use only. This will read the "global"
    *                          configuration block in a file, overwriting any default settings on a per-plugin base.
    *                          Any derived or additional attributes must be added through the global() virtual method.
    *
    * @param config	           A Boost property (sub-)tree containing the global block
    * @return	               True if successful, false otherwise
    */
    bool readGlobal(CFG_VAL config) {
        boost::optional<boost::property_tree::iptree&> globalVals = config.get_child_optional("global");
        if (globalVals) {
            BOOST_FOREACH(boost::property_tree::iptree::value_type &global, config.get_child("global")) {
                if (boost::iequals(global.first, "mqttprefix")) {
                    _mqttPrefix = global.second.data();
                    if (_mqttPrefix[_mqttPrefix.length()-1] != '/') {
                        _mqttPrefix.append("/");
                    }
                    LOG(debug) << "  Using own MQTT-Prefix " << _mqttPrefix;
                } else if (boost::iequals(global.first, "cacheInterval")) {
                    _cacheInterval = stoul(global.second.data());
                    LOG(debug) << "  Using own caching interval " << _cacheInterval << " [s]";
                    _cacheInterval *= 1000;
Alessio Netti's avatar
Alessio Netti committed
532
533
                } else if (boost::iequals(global.first, "sensorpattern")) {
                    _sensorPattern = global.second.data();
Alessio Netti's avatar
Alessio Netti committed
534
535
536
537
538
539
540
                }
            }
            global(config.get_child("global"));
        }
        return true;
    }

Alessio Netti's avatar
Alessio Netti committed
541
542
543
544
545
    /**
    * @brief                   Adjusts the names of the sensors
    *
    *                          Names are modified according to the sensorPattern specified in the global
    *                          settings. Operates in tandem with the auto-publish feature.
Alessio Netti's avatar
Alessio Netti committed
546
547
    *
    * @return                  true if successful, false otherwise
Alessio Netti's avatar
Alessio Netti committed
548
    */
549
    //TODO: switch to textual MQTT topics and use only MQTTPrefix
Alessio Netti's avatar
Alessio Netti committed
550
    bool constructSensorNames(UnitTemplate<SBase>& u, Analyzer& an) {
Alessio Netti's avatar
Alessio Netti committed
551
552
553
554
        boost::regex sensorReg(SENSOR_PATTERN), groupReg(GROUP_PATTERN);
        boost::cmatch match;
        //TODO: move sensorpattern checks somewhere else
        if(_sensorPattern == "")
Alessio Netti's avatar
Alessio Netti committed
555
            return true;
Alessio Netti's avatar
Alessio Netti committed
556
        else if (!boost::regex_search(_sensorPattern.c_str(), match, sensorReg)) {
Alessio Netti's avatar
Alessio Netti committed
557
558
            LOG(error) << "Invalid sensor naming pattern " << _sensorPattern << ". You must at least include <sensor>!";
            return false;
Alessio Netti's avatar
Alessio Netti committed
559
560
561
562
563
564
565
566
567
        }

        std::string name;
        // Performing name construction
        for(auto& s: u.getOutputs()) {
            name = s->getName();
            // If the unit is related to a system component all of its sensors will have their names adjusted already
            // If it is root, then we apply normal auto-publish. This means that adding the analyzer's name
            // or plugin ID do not always work, as of now
568
            if( u.getName() == SensorNavigator::rootKey) {
Alessio Netti's avatar
Alessio Netti committed
569
570
571
572
573
574
                name = _sensorPattern;
                name = boost::regex_replace(name, sensorReg, s->getName());
                name = boost::regex_replace(name, groupReg, an.getName());
            }
            s->setName(name);
        }
Alessio Netti's avatar
Alessio Netti committed
575
        return true;
Alessio Netti's avatar
Alessio Netti committed
576
577
    }

Alessio Netti's avatar
Alessio Netti committed
578
    // Instance of a QueryEngine object
579
    QueryEngine&     _queryEngine;
Alessio Netti's avatar
Alessio Netti committed
580
581
    // UnitGenerator object used to create units
    UnitGenerator<SBase>    _unitGen;
Alessio Netti's avatar
Alessio Netti committed
582
583
584
585
586
587
588
589
590
591

    // Keyword used to identify analyzer blocks in config files
    std::string		_analyzerName;
    // Keyword used to identify sensors in config files
    std::string     _baseName;

    // Path of the configuration file that must be used
    std::string 	_cfgPath;
    // Default MQTT prefix to be used when creating output sensors
    std::string		_mqttPrefix;
Alessio Netti's avatar
Alessio Netti committed
592
593
    // String used to construct sensor names
    std::string     _sensorPattern;
Alessio Netti's avatar
Alessio Netti committed
594
595
596
597
598
599
600
601
    // Interval in seconds for the cache of each sensor
    unsigned int	_cacheInterval;
    // The vector of analyzers, in the form of pointers to AnalyzerInterface objects
    std::vector<AnalyzerPtr> 	_analyzerInterfaces;
    // Like the above, but containing the analyzers in their actual types
    std::vector<A_Ptr>		_analyzers;
    // Map of the template analyzers that were defined in the config file - used for easy retrieval and instantiation
    std::map<std::string, Analyzer*> _templateAnalyzers;
Alessio Netti's avatar
Alessio Netti committed
602
603
604
605
    // Map of the template sensors that were defined
    std::map<std::string, SBase*> _templateSensors;
    // Map of the protoinputs belonging to template analyzers
    std::map<std::string, std::vector<shared_ptr<SBase>>> _templateProtoInputs;
Alessio Netti's avatar
Alessio Netti committed
606
607
608
};

#endif //PROJECT_ANALYZERCONFIGURATORTEMPLATE_H