ConfiguratorTemplate.h 29.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//================================================================================
// Name        : ConfiguratorTemplate.h
// Author      : Micha Mueller, Caral Guillen
// 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 "version.h"
41

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

47
//#define STRCMP(node,str) boost::iequals(node.first,str) //DEPRECATED
Micha Mueller's avatar
Micha Mueller committed
48
#define CFG_VAL	boost::property_tree::iptree&
49

50
#define ADD						BOOST_FOREACH(boost::property_tree::iptree::value_type &val, config)
51
#define ATTRIBUTE(name,setter)		do { if (boost::iequals(val.first, name)) { s.setter(val.second.data()); } } while(0)
Micha Mueller's avatar
Micha Mueller committed
52
#define SETTING(name)				if (boost::iequals(val.first, name))
53

54
55
#define DEFAULT_CACHE_INTERVAL 900000

Micha Mueller's avatar
Micha Mueller committed
56
/**
57
58
59
 * @brief Interface template for plugin configurator implementations.
 *
 * @ingroup pusherplugins
Micha Mueller's avatar
Micha Mueller committed
60
 */
61
template <class SBase, class SGroup, class SEntity = nullptr_t>
62
class ConfiguratorTemplate : public ConfiguratorInterface {
63
	//the template shall only be instantiated for classes which derive from SensorBase/SensorGroup
64
	static_assert(std::is_base_of<SensorBase, SBase>::value, "SBase must derive from SensorBase!");
65
	static_assert(std::is_base_of<SensorGroupInterface, SGroup>::value, "SGroup must derive from SensorGroupInterface!");
66

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

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

75
76
77
78
	const char COMMA = ',';
	const char OPEN_SQBRKET = '[';
	const char CLOSE_SQBRKET = ']';
	const char DASH = '-';
79
	
80
public:
81
	ConfiguratorTemplate() :
82
83
84
		_entityName("INVALID"),
		_groupName("INVALID"),
		_baseName("INVALID"),
85
86
		_cfgPath(""),
		_mqttPrefix(""),
87
		_cacheInterval(DEFAULT_CACHE_INTERVAL) {}
88

89
90
	ConfiguratorTemplate(const ConfiguratorTemplate&) = delete;

91
	virtual ~ConfiguratorTemplate() {
92
93
94
		for (auto e : _sensorEntitys) {
			delete e;
		}
Michael Ott's avatar
Michael Ott committed
95
96
97
		for (auto tb : _templateSensorBases) {
			delete tb.second;
		}
98
		for (auto tg : _templateSensorGroups) {
99
			delete tg.second;
100
101
		}
		for (auto te : _templateSensorEntitys) {
102
			delete te.second;
103
		}
104
		_sensorGroupInterfaces.clear();
105
106
		_sensorGroups.clear();
		_sensorEntitys.clear();
Michael Ott's avatar
Michael Ott committed
107
		_templateSensorBases.clear();
108
		_templateSensorGroups.clear();
109
		_templateSensorEntitys.clear();
110
	}
111

112
113
	ConfiguratorTemplate& operator=(const ConfiguratorTemplate&) = delete;

114
115
116
	std::string getVersion() {
		return std::string(VERSION);
	}
Micha Mueller's avatar
Micha Mueller committed
117
118
	/**
	 * Read in the given configuration
119
	 *
120
121
	 * Overwriting this method is only required if a custom logic is really necessary!
	 *
Micha Mueller's avatar
Micha Mueller committed
122
	 * @param	cfgPath Path to the config-file
123
124
	 *
	 * @return	True on success, false otherwise
Micha Mueller's avatar
Micha Mueller committed
125
	 */
126
	bool readConfig(std::string cfgPath) {
127
		_cfgPath = cfgPath;
128
129
130
131
132

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

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

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

	/**
Alessio Netti's avatar
Alessio Netti committed
278
	 * Clear internal storage and returns the plugin to the uninitialized state.
279
	 */
Alessio Netti's avatar
Alessio Netti committed
280
	void clearConfig() final {
Micha Mueller's avatar
Micha Mueller committed
281
282
		//bring everything to a halt
		for(auto g : _sensorGroups) {
283
			g->stop();
Micha Mueller's avatar
Micha Mueller committed
284
285
286
287
288
289
		}

		//wait until everything is halted
		for(auto g : _sensorGroups) {
			g->wait();
		}
290

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

	/**
	 * Clear internal storage and read in the configuration again.
	 *
	 * @return	True on success, false otherwise
	 */
	bool reReadConfig() final {
		clearConfig();
319

Micha Mueller's avatar
Micha Mueller committed
320
		//back to the very beginning
321
		return readConfig(_cfgPath);
322
	}
323

324
325
326
327
328
	/**
	 * Print configuration as read in.
	 *
	 * @param ll    Logging level to log with
	 */
329
	void printConfig(LOG_LEVEL ll) final {
330
	  LOG_VAR(ll) << "    General: ";
331
	  if (_mqttPrefix != "") {
332
	    LOG_VAR(ll) << "        MQTT-Prefix: " << _mqttPrefix;
333
	  } else {
334
	    LOG_VAR(ll) << "        MQTT-Prefix: DEFAULT";
335
336
	  }
	  if (_cacheInterval != DEFAULT_CACHE_INTERVAL) {
337
	    LOG_VAR(ll) << "        Cache interval: " << _cacheInterval << " ms";
338
	  } else {
339
	    LOG_VAR(ll) << "        Cache interval: DEFAULT";
340
341
	  }

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

345
	  LOG_VAR(ll) << "    Groups:";
346
	  for(auto g : _sensorGroups) {
347
348
349
	    g->SensorGroupInterface::printConfig(ll);
	    g->printConfig(ll);
	    g->SensorGroupTemplate<SBase>::printConfig(ll);
350
351
352
	  }
	}

353
354
355
356
357
358
359
	/**
	 * Sets internal variables with the ones provided by pluginSettings.
	 * This method should be called once after constructing a configurator
	 * to provide him with the global default values.
	 *
	 * @param pluginSettings	Struct with global default settings for the plugins.
	 */
360
	void setGlobalSettings(const pluginSettings_t& pluginSettings) final {
361
362
		_mqttPrefix = pluginSettings.mqttPrefix;
		_cacheInterval = pluginSettings.cacheInterval;
363
		derivedSetGlobalSettings(pluginSettings);
364
365
	}

Micha Mueller's avatar
Micha Mueller committed
366
367
368
369
370
	/**
	 * Get all sensor groups
	 *
	 * @return	Vector containing pointers to all sensor groups of this plugin
	 */
371
	std::vector<SGroupPtr>& getSensorGroups() final {
372
373
374
		return _sensorGroupInterfaces;
	}

375
protected:
376
	void storeSensorGroup(SG_Ptr sGroup) {
377
378
		_sensorGroups.push_back(sGroup);
		_sensorGroupInterfaces.push_back(sGroup);
Micha Mueller's avatar
Micha Mueller committed
379
380
	}

381
382
	/**
	 * Non-virtual interface method for class-internal use only.
383
	 * Reads and sets the common base values of a sensor base (currently none),
384
385
	 * then calls the corresponding derived function to read plugin specific
	 * values.
386
	 *
387
	 * @param sBase		The sensor base for which to set the values
388
	 * @param config	A boost property (sub-)tree containing the sensor values
389
	 * @param isTemplate	Are we parsing a template or a regular sensor?
390
391
392
	 *
	 * @return	True on success, false otherwise
	 */
393
	bool readSensorBase(SBase& sBase, CFG_VAL config, bool isTemplate=false) {
394
		sBase.setCacheInterval(_cacheInterval);
395
396
397
		if (!isTemplate) {
			boost::optional<boost::property_tree::iptree&> def = config.get_child_optional("default");
			if(def) {
398
				//we copy all values from default
399
400
401
402
403
404
405
406
				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.";
				}
Michael Ott's avatar
Michael Ott committed
407
408
409
			}
		}
		
410
411
412
		BOOST_FOREACH(boost::property_tree::iptree::value_type &val, config) {
			if (boost::iequals(val.first, "mqttsuffix")) {
				sBase.setMqtt(val.second.data());
413
			} else if (boost::iequals(val.first, "skipConstVal")) {
Alessio Netti's avatar
Alessio Netti committed
414
				sBase.setSkipConstVal(to_bool(val.second.data()));
415
			} else if (boost::iequals(val.first, "delta")) {
Alessio Netti's avatar
Alessio Netti committed
416
				sBase.setDelta(to_bool(val.second.data()));
417
418
419
			} 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
420
				sBase.setSubsampling(std::stoul(val.second.data()));
421
			}
422
423
424
		}
		sensorBase(sBase, config);
		return true;
425
426
427
428
	}

	/**
	 * Non-virtual interface method for class-internal use only.
429
430
	 * Reads and sets the common base values of a sensor group, then calls
	 * the corresponding derived function to read in plugin specific values.
431
	 *
432
	 * @param sGroup	The sensor group for which to set the values
433
	 * @param config	A boost property (sub-)tree containing the sensor values
434
	 * @param isTemplate	Is this a template or a regular group?
435
436
437
	 *
	 * @return	True on success, false otherwise
	 */
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
	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.";
				}
453
454
455
			}
		}

456
		//read in values inherited from SensorGroupInterface
457
		BOOST_FOREACH(boost::property_tree::iptree::value_type &val, config) {
458
			if (boost::iequals(val.first, "interval")) {
459
				sGroup.setInterval(stoull(val.second.data()));
460
			} else if (boost::iequals(val.first, "minValues")) {
461
				sGroup.setMinValues(stoull(val.second.data()));
462
463
			} else if (boost::iequals(val.first, "mqttPart")) {
				sGroup.setMqttPart(val.second.data());
464
465
466
467
468
469
			} else if (boost::iequals(val.first, "sync")) {
				if (val.second.data() == "off") {
					sGroup.setSync(false);
				} else {
					sGroup.setSync(true);
				}
470
			} else if (boost::iequals(val.first, _baseName)) {
471
472
473
				if (!isTemplate) {
					LOG(debug) << "  " << _baseName << " " << val.second.data();
				}
474
				SB_Ptr sensor = std::make_shared<SBase>(val.second.data());
475
				if (readSensorBase(*sensor, val.second, isTemplate)) {
476
					sGroup.pushBackSensor(sensor);
477
				} else if (!isTemplate) {
478
					LOG(warning) << _baseName << " " << sGroup.getGroupName() << "::" << sensor->getName() << " could not be read! Omitting";
479
				}
480
481
482
			}
		}

483
484
485
		//TODO keep debug logging for config?
//		LOG(debug) << "  Interval : " << sGroup.getInterval();
//		LOG(debug) << "  minValues: " << sGroup.getMinValues();
486

487
488
		sensorGroup(sGroup, config);
		return true;
489
490
	}

491
492
493
494
495
496
497
	/**
	 * Non-virtual interface method for class-internal use only.
	 * Reads and sets the common base values of a sensor entity, then calls
	 * the corresponding derived function to read in plugin specific values.
	 *
	 * @param sEntity	The aggregating entity for which to set the values
	 * @param config	A boost property (sub-)tree containing the sensor values
Micha Mueller's avatar
Micha Mueller committed
498
499
	 * @param isTemplate	Indicate if sEntity is a template. If so, also store
	 * 						the corresponding sGroups in the template map
500
501
502
	 *
	 * @return	True on success, false otherwise
	 */
Micha Mueller's avatar
Micha Mueller committed
503
	bool readSensorEntity(SEntity& sEntity, CFG_VAL config, bool isTemplate) {
504
505
506
507
508
509
510
		//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()) {
511
				sEntity = *(it->second);
Micha Mueller's avatar
Micha Mueller committed
512
513
				for(auto g : _templateSensorGroups) {
					if (isEntityOfGroup(*(it->second), *(g.second))) {
514
						SG_Ptr group = std::make_shared<SGroup>(*(g.second));
Micha Mueller's avatar
Micha Mueller committed
515
						setEntityForGroup(sEntity, *group);
516
						storeSensorGroup(group);
Micha Mueller's avatar
Micha Mueller committed
517
518
					}
				}
519
520
521
522
			} else {
				LOG(warning) << "Template " << _entityName << "\"" << def.get().data() << "\" not found! Using standard values.";
			}
		}
Micha Mueller's avatar
Micha Mueller committed
523

524
		sensorEntity(sEntity, config);
Micha Mueller's avatar
Micha Mueller committed
525
526
527
528

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

614
		if(!isTemplate) {
615
			for(const auto& g : _sensorGroups) {
616
617
618
				if(isEntityOfGroup(sEntity, *g)) {
					finalizeGroup(*g);
				}
Micha Mueller's avatar
Micha Mueller committed
619
620
			}
		}
621
		return true;
622
623
	}

Micha Mueller's avatar
Micha Mueller committed
624
	bool readGlobal(CFG_VAL config) {
625
626
627
628
629
630
631
632
633
634
635
		boost::optional<boost::property_tree::iptree&> globalVals = config.get_child_optional("global");
		if (globalVals) {
			BOOST_FOREACH(boost::property_tree::iptree::value_type &global, config.get_child("global")) {
				if (boost::iequals(global.first, "mqttprefix")) {
					_mqttPrefix = global.second.data();
					if (_mqttPrefix[_mqttPrefix.length()-1] != '/') {
						_mqttPrefix.append("/");
					}
				} else if (boost::iequals(global.first, "cacheInterval")) {
					_cacheInterval = stoul(global.second.data());
					_cacheInterval *= 1000;
636
				} 
637
			}
638
			global(config.get_child("global"));
639
		}
640
		return true;
641
642
	}

643
	/**
644
	 * Virtual interface method, responsible for setting global values specifically
645
646
647
648
	 * for its plugin.
	 *
	 * @param pluginSettings	The struct with global default plugin settings
	 */
649
650
651
	virtual void derivedSetGlobalSettings(const pluginSettings_t& pluginSettings) {
		//Overwrite if necessary
	}
652
653
654

	/**
	 * Pure virtual interface method, responsible for reading plugin-specific sensor
655
	 * base values.
656
	 *
Micha Mueller's avatar
Micha Mueller committed
657
	 * @param s			The sensor base for which to set the values
658
659
	 * @param config	A boost property (sub-)tree containing the sensor values
	 */
Micha Mueller's avatar
Micha Mueller committed
660
	virtual void sensorBase(SBase& s, CFG_VAL config) = 0;
661
662
663
664
665

	/**
	 * Pure virtual interface method, responsible for reading plugin-specific sensor
	 * group values.
	 *
Micha Mueller's avatar
Micha Mueller committed
666
	 * @param s			The sensor group for which to set the values
667
	 * @param config	A boost property (sub-)tree containing the group values
668
	 */
Micha Mueller's avatar
Micha Mueller committed
669
	virtual void sensorGroup(SGroup& s, CFG_VAL config) = 0;
670

671
672
673
674
	/**
	 * Virtual interface method, responsible for reading plugin-specific sensor
	 * entity values.
	 *
Micha Mueller's avatar
Micha Mueller committed
675
	 * @param s			The sensor entity for which to set the values
676
677
	 * @param config	A boost property (sub-)tree containing the entity values
	 */
Micha Mueller's avatar
Micha Mueller committed
678
	virtual void sensorEntity(SEntity& s, CFG_VAL config) {
679
680
681
		//Overwrite if necessary
		LOG(warning) << "Method sensorEntity called, but was not overwritten! Either you have unwanted entitys in your config file or forgot to overwrite this method";
	}
682

Micha Mueller's avatar
Micha Mueller committed
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
	/**
	 * Check if e is the corresponding entity of g
	 *
	 * @param e
	 * @param g
	 *
	 * @return	True if (g.entity == &e)
	 */
	//TODO not very convenient for writing plugins. Are there better solutions?
	virtual bool isEntityOfGroup(SEntity& e, SGroup& g) {
		//Overwrite if necessary
		LOG(warning) << "Method isEntityOfGroup called, but was not overwritten! Either you have unwanted entitys in your config file or forgot to overwrite this method";
		return false;
	}

	/**
	 * Sets e as entity for group g
	 *
	 * @param e
	 * @param g
	 */
	//TODO not very convenient for writing plugins. Are there better solutions?
	virtual void setEntityForGroup(SEntity& e, SGroup& g) {
		//Overwrite if necessary
		LOG(warning) << "Method setEntityForGroup called, but was not overwritten! Either you have unwanted entitys in your config file or forgot to overwrite this method";
	}

	/**
	 * Finalize the group g with everything it needs from its entity (set e.g. the mqttPart for entity)
	 *
	 * @param g
	 */
	//TODO not very convenient for writing plugins. Are there better solutions?
	virtual void finalizeGroup(SGroup& g) {
		//Overwrite if necessary
		LOG(warning) << "Method finalizeEntityGroup called, but was not overwritten! Either you have unwanted entitys in your config file or forgot to overwrite this method";
	}

721
722
	/**
	 * Print information about configurable configurator attributes (or nothing if no such attributes are required)
723
	 * and associated entities.
724
725
726
727
728
	 *
	 * @param ll    Severity level to log with
	 */
	virtual void printConfiguratorConfig(LOG_LEVEL ll) {
	  //Overwrite if necessary
729
	  LOG_VAR(ll) << "        No other plugin-specific general parameters or entities defined";
730
731
	}

732
733
734
735
736
	/**
	 * Virtual interface method, responsible for reading plugin-specific global values.
	 *
	 * @param config	A boost property (sub-)tree containing the global values
	 */
Micha Mueller's avatar
Micha Mueller committed
737
	virtual void global(CFG_VAL config) {}
738
	
Alessio Netti's avatar
Alessio Netti committed
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
	/**
	 * Tries to parse the given cpuString as integer numbers. On success, the specified numbers will be inserted
	 * into a set, which will be returned. On failure, an empty set is returned. A set is used to maintain uniqueness
	 * and an ascending order among the numbers although this is not strictly required.
	 *
	 * @param cpuString	String which specifies a range and/or set of numbers (e.g. "1,2,3-5,7-9,10")
	 * @return	A set of integers as specified in the cpuString. If the string could not be parsed the set will be empty.
	 */
	std::set<int> parseCpuString(const std::string& cpuString) {
		std::set<int> cpus;
		int maxCpu = 512;

		std::vector<std::string> subStrings;

		std::stringstream ssComma(cpuString);
		std::string item;
		while (std::getline(ssComma, item, ',')) {
			subStrings.push_back(item);
		}

		for (auto s : subStrings) {
			if (s.find('-') != std::string::npos) { //range of values (e.g. 1-5) specified
				std::stringstream ssHyphen(s);
				std::string min, max;
				std::getline(ssHyphen, min, '-');
				std::getline(ssHyphen, max);

				try {
					int minVal = stoi(min);
					int maxVal = stoi(max);

					for (int i = minVal; i <= maxVal; i++) {
						if (i >= 0 && i < maxCpu) {
							cpus.insert((int)i);
						}
					}
				} catch (const std::exception& e) {
					LOG(debug) << "Could not parse values \"" << min << "-" << max << "\"";
				}
			} else { //single value
				try {
					int val = stoi(s);
					if (val >= 0 && val < maxCpu) {
						cpus.insert((int)val);
					}
				} catch (const std::exception& e) {
					LOG(debug) << "Could not parse value \"" << s << "\"";
				}
			}
		}

		if (cpus.empty()) {
			LOG(warning) << "  CPUs could not be parsed!";
		} else {
			std::stringstream sstream;
			sstream << "  CPUS: ";
			for (auto i : cpus) {
				sstream << i << ", ";
			}
			std::string msg = sstream.str();
			msg.pop_back();
			msg.pop_back();
			LOG(debug) << msg;
		}
		return cpus;
	}

Alessio Netti's avatar
Alessio Netti committed
806
	/**
807
	 * @brief 		Adjusts the names of the sensors in generated groups.
Alessio Netti's avatar
Alessio Netti committed
808
809
	 *
	 * @return		true if successful, false otherwise
Alessio Netti's avatar
Alessio Netti committed
810
	 */
811
812
	bool constructSensorTopics() {
		// Sensor names are adjusted according to the respective MQTT topics
Alessio Netti's avatar
Alessio Netti committed
813
814
		for(auto& g: _sensorGroups)
			for(auto& s: g->getSensors()) {
815
816
817
				s->setMqtt(MQTTChecker::formatTopic(_mqttPrefix) + MQTTChecker::formatTopic(g->getMqttPart()) + MQTTChecker::formatTopic(s->getMqtt()));
				s->setName(s->getMqtt());
			}
Alessio Netti's avatar
Alessio Netti committed
818
		return true;
Alessio Netti's avatar
Alessio Netti committed
819
820
	}

821
822
	std::string		_entityName;
	std::string		_groupName;
823
	std::string		_baseName;
824
825
826
827

	std::string 	_cfgPath;
	std::string		_mqttPrefix;
	unsigned int	_cacheInterval;
828
829
	std::vector<SGroupPtr> 	_sensorGroupInterfaces;
	std::vector<SG_Ptr>		_sensorGroups;
830
	std::vector<SEntity*>	_sensorEntitys;
Michael Ott's avatar
Michael Ott committed
831
	sBaseMap_t		_templateSensorBases;
832
833
	sGroupMap_t		_templateSensorGroups;
	sEntityMap_t	_templateSensorEntitys;
834
835
};

836
#endif /* SRC_CONFIGURATORTEMPLATE_H_ */