Currently job artifacts in CI/CD pipelines on LRZ GitLab never expire. Starting from Wed 26.1.2022 the default expiration time will be 30 days (GitLab default). Currently existing artifacts in already completed jobs will not be affected by the change. The latest artifacts for all jobs in the latest successful pipelines will be kept. More information: https://gitlab.lrz.de/help/user/admin_area/settings/continuous_integration.html#default-artifacts-expiration

ConfiguratorTemplate.h 43.9 KB
Newer Older
1
2
//================================================================================
// Name        : ConfiguratorTemplate.h
3
// Author      : Micha Mueller, Carla Guillen
Micha Müller's avatar
Micha Müller committed
4
// Contact     : info@dcdb.it
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 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.
//================================================================================
27

28
29
#ifndef SRC_CONFIGURATORTEMPLATE_H_
#define SRC_CONFIGURATORTEMPLATE_H_
30

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

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

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

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

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

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

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

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

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

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

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

	/**
285
	 * @brief Clear internal storage and return plugin in unconfigured state.
286
	 */
Alessio Netti's avatar
Alessio Netti committed
287
	void clearConfig() final {
288
	    ConfiguratorInterface::clearConfig();
289
290
		// Bring everything to a halt
		for(auto g : _sensorGroups)
291
			g->stop();
292
293
294
		// Wait for stop
		for(auto g : _sensorGroups)
			g->wait();
Micha Mueller's avatar
Micha Mueller committed
295

296
297
298
299
		//clean up sensors/groups/entitys and templates
		for(auto e : _sensorEntitys) {
			delete e;
		}
Michael Ott's avatar
Michael Ott committed
300
301
302
		for (auto tb : _templateSensorBases) {
			delete tb.second;
		}
303
		for (auto tg : _templateSensorGroups) {
304
			delete tg.second;
305
306
		}
		for (auto te : _templateSensorEntitys) {
307
			delete te.second;
308
		}
Micha Mueller's avatar
Micha Mueller committed
309
		_sensorGroups.clear();
310
		_sensorEntitys.clear();
Michael Ott's avatar
Michael Ott committed
311
		_templateSensorBases.clear();
312
		_templateSensorGroups.clear();
313
		_templateSensorEntitys.clear();
Alessio Netti's avatar
Alessio Netti committed
314
315
316
	}

	/**
317
318
319
320
     * @brief Print configuration.
     *
     * @param ll Log severity level to be used from logger.
     */
321
	void printConfig(LOG_LEVEL ll) final {
322
        ConfiguratorInterface::printConfig(ll);
323

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

327
        LOG_VAR(ll) << "    " << _entityName << "s:";
328
329
        if (_sensorEntitys.size() != 0) {
            for(auto e : _sensorEntitys) {
330
331
332
333
334
335
336
                e->printConfig(ll, 8);
		LOG_VAR(ll) << "            Sensor Groups:";
		for(auto g : _sensorGroups) {
		    if (g->getEntity() == e) {
			g->printConfig(ll, 16);
		    }
		}
337
338
            }
        } else {
339
	    LOG_VAR(ll) << "            No " << _entityName << "s present!";
340
        }
341
/*
342
343
344
345
        LOG_VAR(ll) << "    " << _groupName << "s:";
        for(auto g : _sensorGroups) {
            g->printConfig(ll);
        }
346
 */
347
348
	}

349
protected:
Micha Mueller's avatar
Micha Mueller committed
350

351
352
	///@name Template-internal use only
	///@{
353
	/**
354
	 * @brief Read common values of a sensorbase.
355
	 *
356
357
358
359
360
361
362
	 * @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?
363
364
365
	 *
	 * @return	True on success, false otherwise
	 */
366
	bool readSensorBase(SBase& sBase, CFG_VAL config, bool isTemplate=false) {
367
		sBase.setCacheInterval(_cacheInterval);
368
369
370
		if (!isTemplate) {
			boost::optional<boost::property_tree::iptree&> def = config.get_child_optional("default");
			if(def) {
371
				//we copy all values from default
372
373
374
375
376
377
				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 {
378
					LOG(warning) << "Template " << _baseName << "\" " << def.get().data() << "\" not found! Using standard values.";
379
				}
Michael Ott's avatar
Michael Ott committed
380
381
382
			}
		}
		
383
384
385
		BOOST_FOREACH(boost::property_tree::iptree::value_type &val, config) {
			if (boost::iequals(val.first, "mqttsuffix")) {
				sBase.setMqtt(val.second.data());
386
			} else if (boost::iequals(val.first, "skipConstVal")) {
Alessio Netti's avatar
Alessio Netti committed
387
				sBase.setSkipConstVal(to_bool(val.second.data()));
388
			} else if (boost::iequals(val.first, "delta")) {
Alessio Netti's avatar
Alessio Netti committed
389
				sBase.setDelta(to_bool(val.second.data()));
390
			} else if (boost::iequals(val.first, "subSampling")) {
Alessio Netti's avatar
Alessio Netti committed
391
				sBase.setSubsampling(std::stoi(val.second.data()));
392
393
			} else if (boost::iequals(val.first, "publish")) {
				sBase.setPublish(to_bool(val.second.data()));
394
395
396
397
398
399
400
401
			} else if (boost::iequals(val.first, "metadata")) {
				SensorMetadata sm;
				try {
					sm.parsePTREE(val.second);
					sBase.setMetadata(sm);
				} catch(const std::exception& e) {
					LOG(error) << "  Metadata parsing failed for sensor " << sBase.getName() << "!" << std::endl;
				}
402
			}
403
404
405
		}
		sensorBase(sBase, config);
		return true;
406
407
408
	}

	/**
409
410
411
412
413
414
415
416
417
418
419
420
     * @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
     */
421
422
423
424
425
426
427
428
429
430
431
432
433
	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 {
434
435
					LOG(warning) << "Template " << _groupName << "\" "
					             << def.get().data() << "\" not found! Using standard values.";
436
				}
437
438
439
			}
		}

440
		//read in values inherited from SensorGroupInterface
441
		BOOST_FOREACH(boost::property_tree::iptree::value_type &val, config) {
442
			if (boost::iequals(val.first, "interval")) {
443
				sGroup.setInterval(stoull(val.second.data()));
444
			} else if (boost::iequals(val.first, "minValues")) {
445
				sGroup.setMinValues(stoull(val.second.data()));
446
447
			} else if (boost::iequals(val.first, "mqttPart")) {
				sGroup.setMqttPart(val.second.data());
448
			} else if (boost::iequals(val.first, "sync")) {
449
				sGroup.setSync(to_bool(val.second.data()));
450
			} else if (boost::iequals(val.first, "disabled")) {
451
				sGroup.setDisabled(to_bool(val.second.data()));
452
			} else if (boost::iequals(val.first, _baseName)) {
453
454
455
				if (!isTemplate) {
					LOG(debug) << "  " << _baseName << " " << val.second.data();
				}
456
				SB_Ptr sensor = std::make_shared<SBase>(val.second.data());
457
				if (readSensorBase(*sensor, val.second, isTemplate)) {
458
					sGroup.pushBackSensor(sensor);
459
				} else if (!isTemplate) {
460
461
					LOG(warning) << _baseName << " " << sGroup.getGroupName() << "::"
					             << sensor->getName() << " could not be read! Omitting";
462
				}
463
464
465
			}
		}

466
467
		sensorGroup(sGroup, config);
		return true;
468
469
	}

470
	/**
471
472
473
474
475
476
477
478
479
480
481
482
483
484
     * @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) {
485
486
487
488
489
490
491
		//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()) {
492
				sEntity = *(it->second);
493
				sEntity.setName(config.data());
Micha Mueller's avatar
Micha Mueller committed
494
				for(auto g : _templateSensorGroups) {
495
					if (it->second == g.second->getEntity()) {
496
						SG_Ptr group = std::make_shared<SGroup>(*(g.second));
497
						group->setEntity(&sEntity);
498
499
500
501
502
						if (group->getGroupName().size() > 0) {
							group->setGroupName(sEntity.getName() + "::" + group->getGroupName());
						} else {
							group->setGroupName(sEntity.getName());
						}
503
						storeSensorGroup(group);
Micha Mueller's avatar
Micha Mueller committed
504
505
					}
				}
506
			} else {
507
508
				LOG(warning) << "Template " << _entityName << "\""
				             << def.get().data() << "\" not found! Using standard values.";
509
510
			}
		}
Micha Mueller's avatar
Micha Mueller committed
511

Micha Müller's avatar
Micha Müller committed
512
        //read in values inherited from EntityInterface
513
514
515
516
		BOOST_FOREACH(boost::property_tree::iptree::value_type &val, config) {
			if (boost::iequals(val.first, "mqttPart")) {
				sEntity.setMqttPart(val.second.data());
			} else if (boost::iequals(val.first, "disabled")) {
517
				sEntity.setDisabled(to_bool(val.second.data()));
518
519
			}
		}
Micha Müller's avatar
Micha Müller committed
520

521
		sensorEntity(sEntity, config);
Micha Mueller's avatar
Micha Mueller committed
522
523
524
525

		BOOST_FOREACH(boost::property_tree::iptree::value_type &val, config) {
			if (boost::iequals(val.first, _groupName)) {
				LOG(debug) << "  " << _groupName << " " << val.second.data();
526
				if (!val.second.empty()) {
527
528
529
					if (isTemplate) {
						SGroup* group = new SGroup(val.second.data());
						if(readSensorGroup(*group, val.second)) {
530
						    group->setEntity(&sEntity);
531
							auto ret = _templateSensorGroups.insert(std::pair<std::string, SGroup*>(sEntity.getName() + "::" + group->getGroupName(), group));
532
							if(!ret.second) {
533
								LOG(warning) << "Template " << _groupName << " "
534
								             << sEntity.getName() + "::" + group->getGroupName() << " already exists! Omitting...";
535
536
537
								delete group;
							}
						} else {
538
539
							LOG(warning) << _groupName << " " << group->getGroupName()
							             << " could not be read! Omitting";
540
							delete group;
Micha Mueller's avatar
Micha Mueller committed
541
542
						}
					} else {
543
544
						SG_Ptr group = std::make_shared<SGroup>(val.second.data());
						if(readSensorGroup(*group, val.second)) {
545
						    group->setEntity(&sEntity);
546
547
548
549
550
551
						    if (group->getGroupName().size() > 0) {
							group->setGroupName(sEntity.getName() + "::" + group->getGroupName());
						    } else {
							group->setGroupName(sEntity.getName());
						    }
						    storeSensorGroup(group);
552
						} else {
553
554
							LOG(warning) << _groupName << " " << group->getGroupName()
							             << " could not be read! Omitting";
555
						}
556
557
558
559
560
					}
				}
			} else if (boost::iequals(val.first, "single_" + _baseName)) {
				LOG(debug) << "Single " << _baseName << " \"" << val.second.data() << "\"";
				if (!val.second.empty()) {
561
562
563
564
					if (isTemplate) {
						SGroup* group = new SGroup(val.second.data());
						//group which consists of only one sensor
						if (readSensorGroup(*group, val.second)) {
565
						    group->setEntity(&sEntity);
566
							SB_Ptr sensor = std::make_shared<SBase>(val.second.data());
567
568
569
570
							if (readSensorBase(*sensor, val.second)) {
								group->pushBackSensor(sensor);
								auto ret = _templateSensorGroups.insert(std::pair<std::string, SGroup*>(val.second.data(), group));
								if(!ret.second) {
571
572
									LOG(warning) << "Template single " << _baseName << " "
									             << val.second.data() << " already exists! Omitting...";
573
574
575
									delete group;
								}
							} else {
576
577
								LOG(warning) << "Template single " << _baseName << " "
								             << val.second.data() << " could not be read! Omitting";
578
579
580
								delete group;
							}
						} else {
581
582
							LOG(warning) << "Single " << _baseName << " \""
							             << val.second.data() << "\" has bad values! Ignoring...";
583
584
585
586
587
588
							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)) {
589
						    group->setEntity(&sEntity);
590
							SB_Ptr sensor;
591
							//perhaps one sensor is already present because it was copied from the template group
592
							if (group->acquireSensors().size() != 0) {
593
594
595
							    group->releaseSensors();
								sensor = std::dynamic_pointer_cast<SBase>(group->acquireSensors()[0]);
								group->releaseSensors();
596
597
598
599
600
601
								//check if cast was successful (sensor != nullptr)
								if (sensor) {
									sensor->setName(val.second.data());
									if (readSensorBase(*sensor, val.second)) {
										storeSensorGroup(group);
									} else {
602
603
										LOG(warning) << "Single " << _baseName << " "
										             << val.second.data() << " could not be read! Omitting";
604
									}
605
								} else {
606
607
									LOG(warning) << "Single " << _baseName << " "
									             << val.second.data() << " had a type mismatch when casting! Omitting";
608
609
								}
							} else {
610
							    group->releaseSensors();
611
								sensor = std::make_shared<SBase>(val.second.data());
612
613
614
615
								if (readSensorBase(*sensor, val.second)) {
									group->pushBackSensor(sensor);
									storeSensorGroup(group);
								} else {
616
617
									LOG(warning) << "Single " << _baseName << " "
									             << val.second.data() << " could not be read! Omitting";
618
619
								}
							}
620
						} else {
621
622
							LOG(warning) << "Single " << _baseName << " \""
							             << val.second.data() << "\" has bad values! Ignoring...";
623
						}
Micha Mueller's avatar
Micha Mueller committed
624
625
626
627
628
					}
				}
			}
		}

629
		return true;
630
	}
631
	///@}
632

633
634
	///@name Overwrite in plugin
	///@{
635
	/**
636
	 * Method responsible for reading plugin-specific sensor base values.
637
	 *
Micha Mueller's avatar
Micha Mueller committed
638
	 * @param s			The sensor base for which to set the values
639
640
	 * @param config	A boost property (sub-)tree containing the sensor values
	 */
Micha Mueller's avatar
Micha Mueller committed
641
	virtual void sensorBase(SBase& s, CFG_VAL config) = 0;
642
643

	/**
644
	 * Method responsible for reading plugin-specific sensor group values.
645
	 *
Micha Mueller's avatar
Micha Mueller committed
646
	 * @param s			The sensor group for which to set the values
647
	 * @param config	A boost property (sub-)tree containing the group values
648
	 */
Micha Mueller's avatar
Micha Mueller committed
649
	virtual void sensorGroup(SGroup& s, CFG_VAL config) = 0;
650

651
	/**
652
	 * Method responsible for reading plugin-specific sensor entity values.
653
	 *
Micha Mueller's avatar
Micha Mueller committed
654
	 * @param s			The sensor entity for which to set the values
655
656
	 * @param config	A boost property (sub-)tree containing the entity values
	 */
657
658
	virtual void sensorEntity(SEntity& s, CFG_VAL config) = 0;
	///@}
659

660
661
662
663
664
665
666
667
668
669
670
	///@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
671
672

	/**
673
	 * @brief Adjusts the names of the sensors in generated groups.
Micha Mueller's avatar
Micha Mueller committed
674
	 *
675
	 * @return True if successful, false otherwise.
Alessio Netti's avatar
Alessio Netti committed
676
	 */
677
678
	bool constructSensorTopics() {
		// Sensor names are adjusted according to the respective MQTT topics
679
680
		for(auto& g: _sensorGroups) {
			for(auto& s: g->acquireSensors()) {
681
682
683
684
				s->setMqtt(MQTTChecker::formatTopic(_mqttPrefix) +
				           MQTTChecker::formatTopic(g->getEntity()->getMqttPart()) +
				           MQTTChecker::formatTopic(g->getMqttPart()) +
				           MQTTChecker::formatTopic(s->getMqtt()));
685
				s->setName(s->getMqtt());
686
687
688
				SensorMetadata* sm = s->getMetadata();
				if(sm) {
					sm->publicName = s->getMqtt();
689
					sm->pattern = s->getMqtt();
690
691
					sm->isVirtual  = false;
				}
692
			}
693
694
			g->releaseSensors();
		}
Alessio Netti's avatar
Alessio Netti committed
695
		return true;
Alessio Netti's avatar
Alessio Netti committed
696
	}
697
	///@}
Alessio Netti's avatar
Alessio Netti committed
698

699
700
	std::string		_entityName;
	std::string		_groupName;
701
	std::string		_baseName;
702

703
	std::vector<SG_Ptr>		_sensorGroups;
704
	std::vector<SEntity*>	_sensorEntitys;
Michael Ott's avatar
Michael Ott committed
705
	sBaseMap_t		_templateSensorBases;
706
707
	sGroupMap_t		_templateSensorGroups;
	sEntityMap_t	_templateSensorEntitys;
708
709
};

710
711
712
713
714
715
716
717

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


/**
 * @brief Partial interface template specialization for plugin configurator
718
 *        implementations without entities.
719
 *
720
721
722
723
724
725
 * @details There is a general template for plugins with entities, see
 *          ConfiguratorTemplate. Common code is moved to ConfiguratorInterface
 *          if possible. If not, common code has to be duplicated and maintained
 *          twice here and in ConfiguratorTemplate. However, having two
 *          templates for cases with and without entities allows for simplified
 *          derived plugin configurators.
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
 *
 * @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
865
866
867
868
                        if (group->acquireSensors().size() != 0) {
                            group->releaseSensors();
                            sensor = std::dynamic_pointer_cast<SBase>(group->acquireSensors()[0]);
                            group->releaseSensors();
869
870
871
872
873
874
875
876
877
878
879
880
881
882
                            //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 {
883
                            group->releaseSensors();
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
                            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();
912
913
        // Bring everything to a halt
        for(auto g : _sensorGroups) 
914
            g->stop();
915
916
917
		// Wait for stop
		for(auto g : _sensorGroups) 
			g->wait();
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

        //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, "subSampling")) {
Alessio Netti's avatar
Alessio Netti committed
991
                sBase.setSubsampling(std::stoi(val.second.data()));
992
993
994
            } else if (boost::iequals(val.first, "publish")) {
				sBase.setPublish(to_bool(val.second.data()));
			} else if (boost::iequals(val.first, "metadata")) {
995
996
997
998
999
1000
1001
1002
				SensorMetadata sm;
				try {
					sm.parsePTREE(val.second);
					sBase.setMetadata(sm);
				} catch(const std::exception& e) {
					LOG(error) << "  Metadata parsing failed for sensor " << sBase.getName() << "!" << std::endl;
				}
			}
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
        }
        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</