ConfiguratorTemplate.h 41.6 KB
Newer Older
1
2
//================================================================================
// Name        : ConfiguratorTemplate.h
3
// Author      : Micha Mueller, Carla Guillen
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Copyright   : Leibniz Supercomputing Centre
// Description : Interface template for plugin configurators.
//================================================================================

//================================================================================
// This file is part of DCDB (DataCenter DataBase)
// Copyright (C) 2018-2019 Leibniz Supercomputing Centre
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//================================================================================
26

27
28
#ifndef SRC_CONFIGURATORTEMPLATE_H_
#define SRC_CONFIGURATORTEMPLATE_H_
29

30
#include <map>
Alessio Netti's avatar
Alessio Netti committed
31
#include <set>
32
33
34
35
36

#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/info_parser.hpp>
37
#include "ConfiguratorInterface.h"
38
#include "sensorbase.h"
39
#include "SensorGroupTemplate.h"
40
#include "EntityInterface.h"
41

42
#include <algorithm>
Alessio Netti's avatar
Alessio Netti committed
43
44
45
46
#include <iostream>
#include <sstream>
#include <iomanip>

47
//TODO cross reference partial template specialization in doxygen docs
Micha Mueller's avatar
Micha Mueller committed
48
/**
49
50
 * @brief Interface template for plugin configurator implementations.
 *
51
52
53
54
55
56
57
 * @details There is a partial template specialization for SEntity = nullptr_t,
 *          i.e. for plugins without entities. Common code is moved to
 *          ConfiguratorInterface if possible. If not, common code has to be
 *          duplicated and maintained twice here and in the template
 *          specialization. However, having two templates for cases with and
 *          without entities allows for easier derived plugin configurators.
 *
58
 * @ingroup pusherplugins
Micha Mueller's avatar
Micha Mueller committed
59
 */
60
template <class SBase, class SGroup, class SEntity = nullptr_t>
61
class ConfiguratorTemplate : public ConfiguratorInterface {
62
	//the template shall only be instantiated for classes which derive from SensorBase/SensorGroup
63
	static_assert(std::is_base_of<SensorBase, SBase>::value, "SBase must derive from SensorBase!");
64
	static_assert(std::is_base_of<SensorGroupInterface, SGroup>::value, "SGroup must derive from SensorGroupInterface!");
65
	static_assert(std::is_base_of<EntityInterface, SEntity>::value, "SEntity must derive from EntityInterface!");
66

67
protected:
68
	//TODO use smart pointers
Michael Ott's avatar
Michael Ott committed
69
	typedef std::map<std::string, SBase*> sBaseMap_t;
70
71
	typedef std::map<std::string, SGroup*> sGroupMap_t;
	typedef std::map<std::string, SEntity*> sEntityMap_t;
72

73
74
	using SB_Ptr = std::shared_ptr<SBase>;
	using SG_Ptr = std::shared_ptr<SGroup>;
75
	
76
public:
77
	ConfiguratorTemplate() :
78
	    ConfiguratorInterface(),
79
80
		_entityName("INVALID"),
		_groupName("INVALID"),
81
		_baseName("INVALID"){}
82

83
	virtual ~ConfiguratorTemplate() {
84
85
86
		for (auto e : _sensorEntitys) {
			delete e;
		}
Michael Ott's avatar
Michael Ott committed
87
88
89
		for (auto tb : _templateSensorBases) {
			delete tb.second;
		}
90
		for (auto tg : _templateSensorGroups) {
91
			delete tg.second;
92
93
		}
		for (auto te : _templateSensorEntitys) {
94
			delete te.second;
95
		}
96
97
		_sensorGroups.clear();
		_sensorEntitys.clear();
Michael Ott's avatar
Michael Ott committed
98
		_templateSensorBases.clear();
99
		_templateSensorGroups.clear();
100
		_templateSensorEntitys.clear();
101
	}
102

Micha Mueller's avatar
Micha Mueller committed
103
	/**
104
	 * @brief Read in the given configuration
105
	 *
106
	 * @details Overwriting this method is only required if a custom logic is really necessary!
107
	 *
Micha Mueller's avatar
Micha Mueller committed
108
	 * @param	cfgPath Path to the config-file
109
110
	 *
	 * @return	True on success, false otherwise
Micha Mueller's avatar
Micha Mueller committed
111
	 */
112
	bool readConfig(std::string cfgPath) {
113
		_cfgPath = cfgPath;
114
115
116
117
118

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

		//read global variables (if present overwrite those from global.conf)
119
120
		readGlobal(cfg);

121
122
123
124
125
126
		//read groups and templates for groups. If present also entity/-template stuff
		BOOST_FOREACH(boost::property_tree::iptree::value_type &val, cfg) {
			//template entity
			if (boost::iequals(val.first, "template_" + _entityName)) {
				LOG(debug) << "Template " << _entityName << " \"" << val.second.data() << "\"";
				if (!val.second.empty()) {
Micha Mueller's avatar
Micha Mueller committed
127
					//name of an entity is only used to identify templates and is not stored otherwise
128
					SEntity* entity = new SEntity(val.second.data());
Micha Mueller's avatar
Micha Mueller committed
129
					if (readSensorEntity(*entity, val.second, true)) {
130
						auto ret = _templateSensorEntitys.insert(std::pair<std::string, SEntity*>(val.second.data(), entity));
131
						if(!ret.second) {
132
133
							LOG(warning) << "Template " << _entityName << " "
							             << val.second.data() << " already exists! Omitting...";
Micha Mueller's avatar
Micha Mueller committed
134
							delete entity;
135
136
						}
					} else {
137
138
						LOG(warning) << "Template " << _entityName << " \""
						             << val.second.data() << "\" has bad values! Ignoring...";
Micha Mueller's avatar
Micha Mueller committed
139
						delete entity;
140
141
142
143
144
145
146
					}
				}
			//template group
			} else if (boost::iequals(val.first, "template_" + _groupName)) {
				LOG(debug) << "Template " << _groupName << " \"" << val.second.data() << "\"";
				if (!val.second.empty()) {
					SGroup* group = new SGroup(val.second.data());
147
					if (readSensorGroup(*group, val.second, true)) {
148
						auto ret = _templateSensorGroups.insert(std::pair<std::string, SGroup*>(val.second.data(), group));
149
						if(!ret.second) {
150
151
							LOG(warning) << "Template " << _groupName << " "
							             << val.second.data() << " already exists! Omitting...";
Micha Mueller's avatar
Micha Mueller committed
152
							delete group;
153
						}
154
					} else {
155
156
						LOG(warning) << "Template " << _groupName << " \""
						             << val.second.data() << "\" has bad values! Ignoring...";
Micha Mueller's avatar
Micha Mueller committed
157
						delete group;
158
159
					}
				}
Michael Ott's avatar
Michael Ott committed
160
161
162
163
164
			//template base
			} 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());
165
					if (readSensorBase(*base, val.second, true)) {
Michael Ott's avatar
Michael Ott committed
166
167
						auto ret = _templateSensorBases.insert(std::pair<std::string, SBase*>(val.second.data(), base));
						if(!ret.second) {
168
169
							LOG(warning) << "Template " << _baseName << " "
							             << val.second.data() << " already exists! Omitting...";
Michael Ott's avatar
Michael Ott committed
170
171
172
							delete base;
						}
					} else {
173
174
						LOG(warning) << "Template " << _baseName << " \""
						             << val.second.data() << "\" has bad values! Ignoring...";
Michael Ott's avatar
Michael Ott committed
175
176
177
						delete base;
					}
				}
178
179
180
181
182
			//template single sensor
			} else if (boost::iequals(val.first, "template_single_" + _baseName)) {
				LOG(debug) << "Template single " << _baseName << " \"" << val.second.data() << "\"";
				if (!val.second.empty()) {
					SGroup* group = new SGroup(val.second.data());
183
					if (readSensorGroup(*group, val.second, true)) {
184
						//group which consists of only one sensor
185
						SB_Ptr sensor = std::make_shared<SBase>(val.second.data());
186
						if (readSensorBase(*sensor, val.second, true)) {
187
188
189
							group->pushBackSensor(sensor);
							auto ret = _templateSensorGroups.insert(std::pair<std::string, SGroup*>(val.second.data(), group));
							if(!ret.second) {
190
191
								LOG(warning) << "Template single " << _baseName << " "
								             << val.second.data() << " already exists! Omitting...";
192
193
194
								delete group;
							}
						} else {
195
196
							LOG(warning) << "Template single " << _baseName << " "
							             << val.second.data() << " could not be read! Omitting";
197
198
199
							delete group;
						}
					} else {
200
201
						LOG(warning) << "Template single " << _baseName << " \""
						             << val.second.data() << "\" has bad values! Ignoring...";
202
203
204
						delete group;
					}
				}
205
206
207
208
			//entity
			} else if (boost::iequals(val.first, _entityName)) {
				LOG(debug) << _entityName << " \"" << val.second.data() << "\"";
				if (!val.second.empty()) {
209
210
					SEntity* entity = new SEntity(val.second.data());
					if (readSensorEntity(*entity, val.second)) {
211
212
						_sensorEntitys.push_back(entity);
					} else {
213
214
						LOG(warning) << _entityName << " \""
						             << val.second.data() << "\" has bad values! Ignoring...";
Micha Mueller's avatar
Micha Mueller committed
215
						delete entity;
216
					}
217
218
219
220
221
				}
			//group
			} else if (boost::iequals(val.first, _groupName)) {
				LOG(debug) << _groupName << " \"" << val.second.data() << "\"";
				if (!val.second.empty()) {
222
					SG_Ptr group = std::make_shared<SGroup>(val.second.data());
223
					if (readSensorGroup(*group, val.second)) {
224
						storeSensorGroup(group);
225
					} else {
226
227
						LOG(warning) << _groupName << " \""
						             << val.second.data() << "\" has bad values! Ignoring...";
228
229
					}
				}
230
231
232
233
			//single sensor
			} else if (boost::iequals(val.first, "single_" + _baseName)) {
				LOG(debug) << "Single " << _baseName << " \"" << val.second.data() << "\"";
				if (!val.second.empty()) {
234
					SG_Ptr group = std::make_shared<SGroup>(val.second.data());
235
236
					if (readSensorGroup(*group, val.second)) {
						//group which consists of only one sensor
237
						SB_Ptr sensor;
238
239
						//perhaps one sensor is already present because it was copied from the template group
						if (group->getSensors().size() != 0) {
240
241
242
243
244
245
246
							sensor = std::dynamic_pointer_cast<SBase>(group->getSensors()[0]);
							//check if cast was successful (sensor != nullptr)
							if (sensor) {
								sensor->setName(val.second.data());
								if (readSensorBase(*sensor, val.second)) {
									storeSensorGroup(group);
								} else {
247
248
									LOG(warning) << "Single " << _baseName << " "
									             << val.second.data() << " could not be read! Omitting";
249
								}
250
							} else {
251
252
								LOG(warning) << "Single " << _baseName << " "
								             << val.second.data() << " had a type mismatch when casting! Omitting";
253
254
							}
						} else {
255
							sensor = std::make_shared<SBase>(val.second.data());
256
257
258
259
							if (readSensorBase(*sensor, val.second)) {
								group->pushBackSensor(sensor);
								storeSensorGroup(group);
							} else {
260
261
								LOG(warning) << "Single " << _baseName << " "
								             << val.second.data() << " could not be read! Omitting";
262
263
264
							}
						}
					} else {
265
266
						LOG(warning) << "Single " << _baseName << " \""
						             << val.second.data() << "\" has bad values! Ignoring...";
267
268
					}
				}
Alessio Netti's avatar
Alessio Netti committed
269
			} else if( !boost::iequals(val.first, "global") ) {
270
271
			    LOG(error) << "\"" << val.first << "\": unknown construct!";
			    return false;
272
273
			}
		}
274
		//read of config finished. Now we build the mqtt-topic for every sensor
275
		return constructSensorTopics();
276
277
278
	}

	/**
279
	 * @brief Clear internal storage and return plugin in unconfigured state.
280
	 */
Alessio Netti's avatar
Alessio Netti committed
281
	void clearConfig() final {
282
	    ConfiguratorInterface::clearConfig();
Micha Mueller's avatar
Micha Mueller committed
283
284
		//bring everything to a halt
		for(auto g : _sensorGroups) {
285
			g->stop();
Micha Mueller's avatar
Micha Mueller committed
286
287
		}

288
289
290
291
		//clean up sensors/groups/entitys and templates
		for(auto e : _sensorEntitys) {
			delete e;
		}
Michael Ott's avatar
Michael Ott committed
292
293
294
		for (auto tb : _templateSensorBases) {
			delete tb.second;
		}
295
		for (auto tg : _templateSensorGroups) {
296
			delete tg.second;
297
298
		}
		for (auto te : _templateSensorEntitys) {
299
			delete te.second;
300
		}
Micha Mueller's avatar
Micha Mueller committed
301
		_sensorGroups.clear();
302
		_sensorEntitys.clear();
Michael Ott's avatar
Michael Ott committed
303
		_templateSensorBases.clear();
304
		_templateSensorGroups.clear();
305
		_templateSensorEntitys.clear();
Alessio Netti's avatar
Alessio Netti committed
306
307
308
	}

	/**
309
310
311
312
     * @brief Print configuration.
     *
     * @param ll Log severity level to be used from logger.
     */
313
	void printConfig(LOG_LEVEL ll) final {
314
        ConfiguratorInterface::printConfig(ll);
315

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

319
320
321
322
323
324
325
326
327
328
329
330
331
        LOG_VAR(ll) << " " << _entityName << "s:";
        if (_sensorEntitys.size() != 0) {
            for(auto e : _sensorEntitys) {
                e->printConfig(ll);
            }
        } else {
            LOG_VAR(ll) << "  No " << _entityName << "s present!";
        }

        LOG_VAR(ll) << "    " << _groupName << "s:";
        for(auto g : _sensorGroups) {
            g->printConfig(ll);
        }
332
333
	}

334
protected:
Micha Mueller's avatar
Micha Mueller committed
335

336
337
	///@name Template-internal use only
	///@{
338
	/**
339
	 * @brief Read common values of a sensorbase.
340
	 *
341
342
343
344
345
346
347
	 * @details Reads and sets the common base values of a sensor base
	 *          (currently none), then calls sensorBase() to read plugin
	 *          specific values.
	 *
	 * @param sBase		 The sensor base for which to set the values.
	 * @param config	 A boost property (sub-)tree containing the values.
	 * @param isTemplate Are we parsing a template or a regular sensor?
348
349
350
	 *
	 * @return	True on success, false otherwise
	 */
351
	bool readSensorBase(SBase& sBase, CFG_VAL config, bool isTemplate=false) {
352
		sBase.setCacheInterval(_cacheInterval);
353
354
355
		if (!isTemplate) {
			boost::optional<boost::property_tree::iptree&> def = config.get_child_optional("default");
			if(def) {
356
				//we copy all values from default
357
358
359
360
361
362
				LOG(debug) << "  Using \"" << def.get().data() << "\" as default.";
				auto it = _templateSensorBases.find(def.get().data());
				if(it != _templateSensorBases.end()) {
					sBase = *(it->second);
					sBase.setName(config.data());
				} else {
363
364
					LOG(warning) << "Template " << _baseName << "\" "
					             << def.get().data() << "\" not found! Using standard values.";
365
				}
Michael Ott's avatar
Michael Ott committed
366
367
368
			}
		}
		
369
370
371
		BOOST_FOREACH(boost::property_tree::iptree::value_type &val, config) {
			if (boost::iequals(val.first, "mqttsuffix")) {
				sBase.setMqtt(val.second.data());
372
			} else if (boost::iequals(val.first, "skipConstVal")) {
Alessio Netti's avatar
Alessio Netti committed
373
				sBase.setSkipConstVal(to_bool(val.second.data()));
374
			} else if (boost::iequals(val.first, "delta")) {
Alessio Netti's avatar
Alessio Netti committed
375
				sBase.setDelta(to_bool(val.second.data()));
376
377
378
			} else if (boost::iequals(val.first, "sink")) {
				sBase.setSinkPath( val.second.data() );
			} else if (boost::iequals(val.first, "subSampling")) {
Alessio Netti's avatar
Alessio Netti committed
379
				sBase.setSubsampling(std::stoul(val.second.data()));
380
			}
381
382
383
		}
		sensorBase(sBase, config);
		return true;
384
385
386
	}

	/**
387
388
389
390
391
392
393
394
395
396
397
398
     * @brief Read common values of a sensorGroup.
     *
     * @details Reads and sets the common base values of a sensor group
     *          (currently none), then calls sensorGroup() to read plugin
     *          specific values.
     *
     * @param sGroup     The sensor group for which to set the values.
     * @param config     A boost property (sub-)tree containing the values.
     * @param isTemplate Are we parsing a template or a regular group?
     *
     * @return  True on success, false otherwise
     */
399
400
401
402
403
404
405
406
407
408
409
410
411
	bool readSensorGroup(SGroup& sGroup, CFG_VAL config, bool isTemplate=false) {
		//first check if default group is given, unless we are reading a template already
		if (!isTemplate) {
			boost::optional<boost::property_tree::iptree&> def = config.get_child_optional("default");
			if(def) {
				//we copy all values from default (including copy constructing its sensors)
				//if own sensors are specified they are appended
				LOG(debug) << "  Using \"" << def.get().data() << "\" as default.";
				auto it = _templateSensorGroups.find(def.get().data());
				if(it != _templateSensorGroups.end()) {
					sGroup = *(it->second);
					sGroup.setGroupName(config.data());
				} else {
412
413
					LOG(warning) << "Template " << _groupName << "\" "
					             << def.get().data() << "\" not found! Using standard values.";
414
				}
415
416
417
			}
		}

418
		//read in values inherited from SensorGroupInterface
419
		BOOST_FOREACH(boost::property_tree::iptree::value_type &val, config) {
420
			if (boost::iequals(val.first, "interval")) {
421
				sGroup.setInterval(stoull(val.second.data()));
422
			} else if (boost::iequals(val.first, "minValues")) {
423
				sGroup.setMinValues(stoull(val.second.data()));
424
425
			} else if (boost::iequals(val.first, "mqttPart")) {
				sGroup.setMqttPart(val.second.data());
426
427
428
429
430
431
			} else if (boost::iequals(val.first, "sync")) {
				if (val.second.data() == "off") {
					sGroup.setSync(false);
				} else {
					sGroup.setSync(true);
				}
432
			} else if (boost::iequals(val.first, _baseName)) {
433
434
435
				if (!isTemplate) {
					LOG(debug) << "  " << _baseName << " " << val.second.data();
				}
436
				SB_Ptr sensor = std::make_shared<SBase>(val.second.data());
437
				if (readSensorBase(*sensor, val.second, isTemplate)) {
438
					sGroup.pushBackSensor(sensor);
439
				} else if (!isTemplate) {
440
441
					LOG(warning) << _baseName << " " << sGroup.getGroupName() << "::"
					             << sensor->getName() << " could not be read! Omitting";
442
				}
443
444
445
			}
		}

446
447
		sensorGroup(sGroup, config);
		return true;
448
449
	}

450
	/**
451
452
453
454
455
456
457
458
459
460
461
462
463
464
     * @brief Read common values of a sensor entity.
     *
     * @details Reads and sets the common base values of a sensor entity
     *          (currently none), then calls sensorEntity() to read plugin
     *          specific values.
     *
     * @param sEntity    The aggregating entity for which to set the values.
     * @param config     A boost property (sub-)tree containing the values.
     * @param isTemplate Indicate if sEntity is a template. If so, also store
     *                   the corresponding sGroups in the template map.
     *
     * @return  True on success, false otherwise
     */
	bool readSensorEntity(SEntity& sEntity, CFG_VAL config, bool isTemplate=false) {
465
466
467
468
469
470
471
		//first check if default entity is given
		boost::optional<boost::property_tree::iptree&> def = config.get_child_optional("default");
		if(def) {
			//we copy all values from default
			LOG(debug) << "  Using \"" << def.get().data() << "\" as default.";
			auto it = _templateSensorEntitys.find(def.get().data());
			if(it != _templateSensorEntitys.end()) {
472
				sEntity = *(it->second);
Micha Mueller's avatar
Micha Mueller committed
473
				for(auto g : _templateSensorGroups) {
474
					if (it->second == g.second->getEntity()) {
475
						SG_Ptr group = std::make_shared<SGroup>(*(g.second));
476
						group->setEntity(&sEntity);
477
						storeSensorGroup(group);
Micha Mueller's avatar
Micha Mueller committed
478
479
					}
				}
480
			} else {
481
482
				LOG(warning) << "Template " << _entityName << "\""
				             << def.get().data() << "\" not found! Using standard values.";
483
484
			}
		}
Micha Mueller's avatar
Micha Mueller committed
485

486
		sensorEntity(sEntity, config);
Micha Mueller's avatar
Micha Mueller committed
487
488
489
490

		BOOST_FOREACH(boost::property_tree::iptree::value_type &val, config) {
			if (boost::iequals(val.first, _groupName)) {
				LOG(debug) << "  " << _groupName << " " << val.second.data();
491
				if (!val.second.empty()) {
492
493
494
					if (isTemplate) {
						SGroup* group = new SGroup(val.second.data());
						if(readSensorGroup(*group, val.second)) {
495
						    group->setEntity(&sEntity);
496
497
							auto ret = _templateSensorGroups.insert(std::pair<std::string, SGroup*>(val.second.data(), group));
							if(!ret.second) {
498
499
								LOG(warning) << "Template " << _groupName << " "
								             << val.second.data() << " already exists! Omitting...";
500
501
502
								delete group;
							}
						} else {
503
504
							LOG(warning) << _groupName << " " << group->getGroupName()
							             << " could not be read! Omitting";
505
							delete group;
Micha Mueller's avatar
Micha Mueller committed
506
507
						}
					} else {
508
509
						SG_Ptr group = std::make_shared<SGroup>(val.second.data());
						if(readSensorGroup(*group, val.second)) {
510
						    group->setEntity(&sEntity);
511
512
							storeSensorGroup(group);
						} else {
513
514
							LOG(warning) << _groupName << " " << group->getGroupName()
							             << " could not be read! Omitting";
515
						}
516
517
518
519
520
					}
				}
			} else if (boost::iequals(val.first, "single_" + _baseName)) {
				LOG(debug) << "Single " << _baseName << " \"" << val.second.data() << "\"";
				if (!val.second.empty()) {
521
522
523
524
					if (isTemplate) {
						SGroup* group = new SGroup(val.second.data());
						//group which consists of only one sensor
						if (readSensorGroup(*group, val.second)) {
525
						    group->setEntity(&sEntity);
526
							SB_Ptr sensor = std::make_shared<SBase>(val.second.data());
527
528
529
530
							if (readSensorBase(*sensor, val.second)) {
								group->pushBackSensor(sensor);
								auto ret = _templateSensorGroups.insert(std::pair<std::string, SGroup*>(val.second.data(), group));
								if(!ret.second) {
531
532
									LOG(warning) << "Template single " << _baseName << " "
									             << val.second.data() << " already exists! Omitting...";
533
534
535
									delete group;
								}
							} else {
536
537
								LOG(warning) << "Template single " << _baseName << " "
								             << val.second.data() << " could not be read! Omitting";
538
539
540
								delete group;
							}
						} else {
541
542
							LOG(warning) << "Single " << _baseName << " \""
							             << val.second.data() << "\" has bad values! Ignoring...";
543
544
545
546
547
548
							delete group;
						}
					} else {
						SG_Ptr group = std::make_shared<SGroup>(val.second.data());
						//group which consists of only one sensor
						if (readSensorGroup(*group, val.second)) {
549
						    group->setEntity(&sEntity);
550
							SB_Ptr sensor;
551
552
							//perhaps one sensor is already present because it was copied from the template group
							if (group->getSensors().size() != 0) {
553
554
555
556
557
558
559
								sensor = std::dynamic_pointer_cast<SBase>(group->getSensors()[0]);
								//check if cast was successful (sensor != nullptr)
								if (sensor) {
									sensor->setName(val.second.data());
									if (readSensorBase(*sensor, val.second)) {
										storeSensorGroup(group);
									} else {
560
561
										LOG(warning) << "Single " << _baseName << " "
										             << val.second.data() << " could not be read! Omitting";
562
									}
563
								} else {
564
565
									LOG(warning) << "Single " << _baseName << " "
									             << val.second.data() << " had a type mismatch when casting! Omitting";
566
567
								}
							} else {
568
								sensor = std::make_shared<SBase>(val.second.data());
569
570
571
572
								if (readSensorBase(*sensor, val.second)) {
									group->pushBackSensor(sensor);
									storeSensorGroup(group);
								} else {
573
574
									LOG(warning) << "Single " << _baseName << " "
									             << val.second.data() << " could not be read! Omitting";
575
576
								}
							}
577
						} else {
578
579
							LOG(warning) << "Single " << _baseName << " \""
							             << val.second.data() << "\" has bad values! Ignoring...";
580
						}
Micha Mueller's avatar
Micha Mueller committed
581
582
583
584
585
					}
				}
			}
		}

586
		return true;
587
	}
588
	///@}
589

590
591
	///@name Overwrite in plugin
	///@{
592
	/**
593
	 * Method responsible for reading plugin-specific sensor base values.
594
	 *
Micha Mueller's avatar
Micha Mueller committed
595
	 * @param s			The sensor base for which to set the values
596
597
	 * @param config	A boost property (sub-)tree containing the sensor values
	 */
Micha Mueller's avatar
Micha Mueller committed
598
	virtual void sensorBase(SBase& s, CFG_VAL config) = 0;
599
600

	/**
601
	 * Method responsible for reading plugin-specific sensor group values.
602
	 *
Micha Mueller's avatar
Micha Mueller committed
603
	 * @param s			The sensor group for which to set the values
604
	 * @param config	A boost property (sub-)tree containing the group values
605
	 */
Micha Mueller's avatar
Micha Mueller committed
606
	virtual void sensorGroup(SGroup& s, CFG_VAL config) = 0;
607

608
	/**
609
	 * Method responsible for reading plugin-specific sensor entity values.
610
	 *
Micha Mueller's avatar
Micha Mueller committed
611
	 * @param s			The sensor entity for which to set the values
612
613
	 * @param config	A boost property (sub-)tree containing the entity values
	 */
614
615
	virtual void sensorEntity(SEntity& s, CFG_VAL config) = 0;
	///@}
616

617
618
619
620
621
622
623
624
625
626
627
	///@name Utility
	///@{
    /**
     * @brief Store a sensor group internally.
     *
     * @param sGroup Group to store.
     */
    void storeSensorGroup(SG_Ptr sGroup) {
        _sensorGroups.push_back(sGroup);
        _sensorGroupInterfaces.push_back(sGroup);
    }
Micha Mueller's avatar
Micha Mueller committed
628
629

	/**
630
	 * @brief Adjusts the names of the sensors in generated groups.
Micha Mueller's avatar
Micha Mueller committed
631
	 *
632
	 * @return True if successful, false otherwise.
Alessio Netti's avatar
Alessio Netti committed
633
	 */
634
635
	bool constructSensorTopics() {
		// Sensor names are adjusted according to the respective MQTT topics
Alessio Netti's avatar
Alessio Netti committed
636
637
		for(auto& g: _sensorGroups)
			for(auto& s: g->getSensors()) {
638
639
640
641
				s->setMqtt(MQTTChecker::formatTopic(_mqttPrefix) +
				           MQTTChecker::formatTopic(g->getEntity()->getMqttPart()) +
				           MQTTChecker::formatTopic(g->getMqttPart()) +
				           MQTTChecker::formatTopic(s->getMqtt()));
642
				s->setName(s->getMqtt());
643
644
				if(s->getSinkPath()!="")
					s->setSinkPath(MQTTChecker::topicToFile(s->getMqtt(), s->getSinkPath()));
645
			}
Alessio Netti's avatar
Alessio Netti committed
646
		return true;
Alessio Netti's avatar
Alessio Netti committed
647
	}
648
	///@}
Alessio Netti's avatar
Alessio Netti committed
649

650
651
	std::string		_entityName;
	std::string		_groupName;
652
	std::string		_baseName;
653

654
	std::vector<SG_Ptr>		_sensorGroups;
655
	std::vector<SEntity*>	_sensorEntitys;
Michael Ott's avatar
Michael Ott committed
656
	sBaseMap_t		_templateSensorBases;
657
658
	sGroupMap_t		_templateSensorGroups;
	sEntityMap_t	_templateSensorEntitys;
659
660
};

661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069

////////////////////////////////////////////////////////////////////////////////
// Partial template specialization for SEntity = nullptr_t
////////////////////////////////////////////////////////////////////////////////


//TODO cross reference partial template specialization in doxygen docs
/**
 * @brief Partial interface template specialization for plugin configurator
 *        implementations.
 *
 * @details There is a general template for plugins with entities. Common code
 *          is moved to ConfiguratorInterface if possible. If not, common code
 *          has to be duplicated and maintained twice here and in the general
 *          template. However, having two templates for cases with and
 *          without entities allows for easier derived plugin configurators.
 *
 * @ingroup pusherplugins
 */
template <class SBase, class SGroup>
class ConfiguratorTemplate<SBase, SGroup, nullptr_t> : public ConfiguratorInterface {
    //the template shall only be instantiated for classes which derive from SensorBase/SensorGroup
    static_assert(std::is_base_of<SensorBase, SBase>::value, "SBase must derive from SensorBase!");
    static_assert(std::is_base_of<SensorGroupInterface, SGroup>::value, "SGroup must derive from SensorGroupInterface!");

protected:
    //TODO use smart pointers
    typedef std::map<std::string, SBase*> sBaseMap_t;
    typedef std::map<std::string, SGroup*> sGroupMap_t;

    using SB_Ptr = std::shared_ptr<SBase>;
    using SG_Ptr = std::shared_ptr<SGroup>;

public:
    ConfiguratorTemplate() :
        ConfiguratorInterface(),
        _groupName("INVALID"),
        _baseName("INVALID"){}

    virtual ~ConfiguratorTemplate() {
        for (auto tb : _templateSensorBases) {
            delete tb.second;
        }
        for (auto tg : _templateSensorGroups) {
            delete tg.second;
        }
        _sensorGroups.clear();
        _templateSensorBases.clear();
        _templateSensorGroups.clear();
    }

    /**
     * @brief Read in the given configuration
     *
     * @details Overwriting this method is only required if a custom logic is really necessary!
     *
     * @param   cfgPath Path to the config-file
     *
     * @return  True on success, false otherwise
     */
    bool readConfig(std::string cfgPath) {
        _cfgPath = cfgPath;

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

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

        //read groups and templates for groups. If present also entity/-template stuff
        BOOST_FOREACH(boost::property_tree::iptree::value_type &val, cfg) {
            //template group
            if (boost::iequals(val.first, "template_" + _groupName)) {
                LOG(debug) << "Template " << _groupName << " \"" << val.second.data() << "\"";
                if (!val.second.empty()) {
                    SGroup* group = new SGroup(val.second.data());
                    if (readSensorGroup(*group, val.second, true)) {
                        auto ret = _templateSensorGroups.insert(std::pair<std::string, SGroup*>(val.second.data(), group));
                        if(!ret.second) {
                            LOG(warning) << "Template " << _groupName << " "
                                         << val.second.data() << " already exists! Omitting...";
                            delete group;
                        }
                    } else {
                        LOG(warning) << "Template " << _groupName << " \""
                                     << val.second.data() << "\" has bad values! Ignoring...";
                        delete group;
                    }
                }
            //template base
            } 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)) {
                        auto ret = _templateSensorBases.insert(std::pair<std::string, SBase*>(val.second.data(), base));
                        if(!ret.second) {
                            LOG(warning) << "Template " << _baseName << " "
                                         << val.second.data() << " already exists! Omitting...";
                            delete base;
                        }
                    } else {
                        LOG(warning) << "Template " << _baseName << " \""
                                     << val.second.data() << "\" has bad values! Ignoring...";
                        delete base;
                    }
                }
            //template single sensor
            } else if (boost::iequals(val.first, "template_single_" + _baseName)) {
                LOG(debug) << "Template single " << _baseName << " \"" << val.second.data() << "\"";
                if (!val.second.empty()) {
                    SGroup* group = new SGroup(val.second.data());
                    if (readSensorGroup(*group, val.second, true)) {
                        //group which consists of only one sensor
                        SB_Ptr sensor = std::make_shared<SBase>(val.second.data());
                        if (readSensorBase(*sensor, val.second, true)) {
                            group->pushBackSensor(sensor);
                            auto ret = _templateSensorGroups.insert(std::pair<std::string, SGroup*>(val.second.data(), group));
                            if(!ret.second) {
                                LOG(warning) << "Template single " << _baseName << " "
                                             << val.second.data() << " already exists! Omitting...";
                                delete group;
                            }
                        } else {
                            LOG(warning) << "Template single " << _baseName << " "
                                         << val.second.data() << " could not be read! Omitting";
                            delete group;
                        }
                    } else {
                        LOG(warning) << "Template single " << _baseName << " \""
                                     << val.second.data() << "\" has bad values! Ignoring...";
                        delete group;
                    }
                }
            //group
            } else if (boost::iequals(val.first, _groupName)) {
                LOG(debug) << _groupName << " \"" << val.second.data() << "\"";
                if (!val.second.empty()) {
                    SG_Ptr group = std::make_shared<SGroup>(val.second.data());
                    if (readSensorGroup(*group, val.second)) {
                        storeSensorGroup(group);
                    } else {
                        LOG(warning) << _groupName << " \""
                                     << val.second.data() << "\" has bad values! Ignoring...";
                    }
                }
            //single sensor
            } else if (boost::iequals(val.first, "single_" + _baseName)) {
                LOG(debug) << "Single " << _baseName << " \"" << val.second.data() << "\"";
                if (!val.second.empty()) {
                    SG_Ptr group = std::make_shared<SGroup>(val.second.data());
                    if (readSensorGroup(*group, val.second)) {
                        //group which consists of only one sensor
                        SB_Ptr sensor;
                        //perhaps one sensor is already present because it was copied from the template group
                        if (group->getSensors().size() != 0) {
                            sensor = std::dynamic_pointer_cast<SBase>(group->getSensors()[0]);
                            //check if cast was successful (sensor != nullptr)
                            if (sensor) {
                                sensor->setName(val.second.data());
                                if (readSensorBase(*sensor, val.second)) {
                                    storeSensorGroup(group);
                                } else {
                                    LOG(warning) << "Single " << _baseName << " "
                                                 << val.second.data() << " could not be read! Omitting";
                                }
                            } else {
                                LOG(warning) << "Single " << _baseName << " "
                                             << val.second.data() << " had a type mismatch when casting! Omitting";
                            }
                        } else {
                            sensor = std::make_shared<SBase>(val.second.data());
                            if (readSensorBase(*sensor, val.second)) {
                                group->pushBackSensor(sensor);
                                storeSensorGroup(group);
                            } else {
                                LOG(warning) << "Single " << _baseName << " "
                                             << val.second.data() << " could not be read! Omitting";
                            }
                        }
                    } else {
                        LOG(warning) << "Single " << _baseName << " \""
                                     << val.second.data() << "\" has bad values! Ignoring...";
                    }
                }
            } else if( !boost::iequals(val.first, "global") ) {
                LOG(error) << "\"" << val.first << "\": unknown construct!";
                return false;
            }
        }
        //read of config finished. Now we build the mqtt-topic for every sensor
        return constructSensorTopics();
    }

    /**
     * @brief Clear internal storage and return plugin in unconfigured state.
     */
    void clearConfig() final {
        ConfiguratorInterface::clearConfig();
        //bring everything to a halt
        for(auto g : _sensorGroups) {
            g->stop();
        }

        //clean up sensors/groups and templates
        for (auto tb : _templateSensorBases) {
            delete tb.second;
        }
        for (auto tg : _templateSensorGroups) {
            delete tg.second;
        }
        _sensorGroups.clear();
        _templateSensorBases.clear();
        _templateSensorGroups.clear();
    }

    /**
     * @brief Print configuration.
     *
     * @param ll Log severity level to be used from logger.
     */
    void printConfig(LOG_LEVEL ll) final {
        ConfiguratorInterface::printConfig(ll);

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

        LOG_VAR(ll) << "    " << _groupName << "s:";
        for(auto g : _sensorGroups) {
            g->printConfig(ll);
        }
    }

protected:

    ///@name Template-internal use only
    ///@{
    /**
     * @brief Read common values of a sensorbase.
     *
     * @details Reads and sets the common base values of a sensor base
     *          (currently none), then calls sensorBase() to read plugin
     *          specific values.
     *
     * @param sBase      The sensor base for which to set the values.
     * @param config     A boost property (sub-)tree containing the values.
     * @param isTemplate Are we parsing a template or a regular sensor?
     *
     * @return  True on success, false otherwise
     */
    bool readSensorBase(SBase& sBase, CFG_VAL config, bool isTemplate=false) {
        sBase.setCacheInterval(_cacheInterval);
        if (!isTemplate) {
            boost::optional<boost::property_tree::iptree&> def = config.get_child_optional("default");
            if(def) {
                //we copy all values from default
                LOG(debug) << "  Using \"" << def.get().data() << "\" as default.";
                auto it = _templateSensorBases.find(def.get().data());
                if(it != _templateSensorBases.end()) {
                    sBase = *(it->second);
                    sBase.setName(config.data());
                } else {
                    LOG(warning) << "Template " << _baseName << "\" "
                                 << def.get().data() << "\" not found! Using standard values.";
                }
            }
        }

        BOOST_FOREACH(boost::property_tree::iptree::value_type &val, config) {
            if (boost::iequals(val.first, "mqttsuffix")) {
                sBase.setMqtt(val.second.data());
            } else if (boost::iequals(val.first, "skipConstVal")) {
                sBase.setSkipConstVal(to_bool(val.second.data()));
            } else if (boost::iequals(val.first, "delta")) {
                sBase.setDelta(to_bool(val.second.data()));
            } else if (boost::iequals(val.first, "sink")) {
                sBase.setSinkPath( val.second.data() );
            } else if (boost::iequals(val.first, "subSampling")) {
                sBase.setSubsampling(std::stoul(val.second.data()));
            }
        }
        sensorBase(sBase, config);
        return true;
    }

    /**
     * @brief Read common values of a sensorGroup.
     *
     * @details Reads and sets the common base values of a sensor group
     *          (currently none), then calls sensorGroup() to read plugin
     *          specific values.
     *
     * @param sGroup     The sensor group for which to set the values.
     * @param config     A boost property (sub-)tree containing the values.
     * @param isTemplate Are we parsing a template or a regular group?
     *
     * @return  True on success, false otherwise
     */
    bool readSensorGroup(SGroup& sGroup, CFG_VAL config, bool isTemplate=false) {
        //first check if default group is given, unless we are reading a template already
        if (!isTemplate) {
            boost::optional<boost::property_tree::iptree&> def = config.get_child_optional("default");
            if(def) {
                //we copy all values from default (including copy constructing its sensors)
                //if own sensors are specified they are appended
                LOG(debug) << "  Using \"" << def.get().data() << "\" as default.";
                auto it = _templateSensorGroups.find(def.get().data());
                if(it != _templateSensorGroups.end()) {
                    sGroup = *(it->second);
                    sGroup.setGroupName(config.data());
                } else {
                    LOG(warning) << "Template " << _groupName << "\" "
                                 << def.get().data() << "\" not found! Using standard values.";
                }
            }
        }

        //read in values inherited from SensorGroupInterface
        BOOST_FOREACH(boost::property_tree::iptree::value_type &val, config) {
            if (boost::iequals(val.first, "interval")) {
                sGroup.setInterval(stoull(val.second.data()));
            } else if (boost::iequals(val.first, "minValues")) {
                sGroup.setMinValues(stoull(val.second.data()));
            } else if (boost::iequals(val.first, "mqttPart")) {
                sGroup.setMqttPart(val.second.data());
            } else if (boost::iequals(val.first, "sync")) {
                if (val.second.data() == "off") {
                    sGroup.setSync(false);
                } else {
                    sGroup.setSync(true);
                }
            } else if (boost::iequals(val.first, _baseName)) {
                if (!isTemplate) {
                    LOG(debug) << "  " << _baseName << " " << val.second.data();
                }
                SB_Ptr sensor = std::make_shared<SBase>(val.second.data());
                if (readSensorBase(*sensor, val.second, isTemplate)) {
                    sGroup.pushBackSensor(sensor);
                } else if (!isTemplate) {
                    LOG(warning) << _baseName << " " << sGroup.getGroupName() << "::"
                                 << sensor->getName() << " could not be read! Omitting";
                }
            }
        }

        sensorGroup(sGroup, config);
        return true;
    }
    ///@}

    ///@name Overwrite in plugin
    ///@{
    /**
     * Method responsible for reading plugin-specific sensor base values.
     *
     * @param s         The sensor base for which to set the values
     * @param config    A boost property (sub-)tree containing the sensor values
     */
    virtual void sensorBase(SBase& s, CFG_VAL config) = 0;

    /**
     * Method responsible for reading plugin-specific sensor group values.
     *
     * @param s         The sensor group for which to set the values
     * @param config    A boost property (sub-)tree containing the group values
     */
    virtual void sensorGroup(SGroup& s, CFG_VAL config) = 0;
    ///@}

    ///@name Utility
    ///@{
    /**
     * @brief Store a sensor group internally.
     *
     * @param sGroup Group to store.
     */
    void storeSensorGroup(SG_Ptr sGroup) {
        _sensorGroups.push_back(sGroup);
        _sensorGroupInterfaces.push_back(sGroup);
    }

    /**
     * @brief Adjusts the names of the sensors in generated groups.
     *
     * @return True if successful, false otherwise.
     */
    bool constructSensorTopics() {
        // Sensor names are adjusted according to the respective MQTT topics
        for(auto& g: _sensorGroups)
            for(auto& s: g->getSensors()) {
                s->setMqtt(MQTTChecker::formatTopic(_mqttPrefix) +
                           MQTTChecker::formatTopic(g->getMqttPart()) +
                           MQTTChecker::formatTopic(s->getMqtt()));
                s->setName(s->getMqtt());
                if(s->getSinkPath()!="")
                    s->setSinkPath(MQTTChecker::topicToFile(s->getMqtt(), s->getSinkPath()));
            }
        return true;
    }
    ///@}

    std::string     _groupName;
    std::string     _baseName;

    std::vector<SG_Ptr>     _sensorGroups;
    sBaseMap_t      _templateSensorBases;
    sGroupMap_t     _templateSensorGroups;
};

1070
#endif /* SRC_CONFIGURATORTEMPLATE_H_ */