SensorGroupTemplate.h 16.2 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        : SensorGroupTemplate.h
// Author      : Micha Mueller
// Copyright   : Leibniz Supercomputing Centre
// Description : Interface template for sensor group functionality.
//================================================================================

//================================================================================
// 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
29

#ifndef SENSORGROUPTEMPLATE_H_
#define SENSORGROUPTEMPLATE_H_

30
#include "SensorGroupInterface.h"
31
#include "EntityInterface.h"
32

33
34
35
#include "timestamp.h"

#include <vector>
36
#include <memory>
37

38
/**
39
40
41
42
43
44
45
 * @brief Interface template for sensor group implementations with entities.
 *
 * @details There is a partial template specialization for E = nullptr_t, i.e.
 *          for groups without entities. 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 greatly
 *          reduces code duplication in derived plugin sensor groups.
46
47
48
 *
 * @ingroup pusherplugins
 */
49
template <class S, class E = nullptr_t>
50
class SensorGroupTemplate : public SensorGroupInterface {
51
	//the template shall only be instantiated for classes which derive from SensorBase and EntityInterface respectively
52
	static_assert(std::is_base_of<SensorBase, S>::value, "S must derive from SensorBase!");
53
	static_assert(std::is_base_of<EntityInterface, E>::value, "E must derive from EntityInterface!");
54

55
56
protected:
	using S_Ptr = std::shared_ptr<S>;
57
	using E_Ptr = std::shared_ptr<E>;
58

59
60
public:
	SensorGroupTemplate(const std::string groupName) :
61
62
		SensorGroupInterface(groupName),
		_entity(nullptr) {}
63

64
	SensorGroupTemplate(const SensorGroupTemplate& other) :
65
66
67
		SensorGroupInterface(other),
		_entity(other._entity) {

68
		for(auto s : other._sensors) {
69
			S_Ptr sensor = std::make_shared<S>(*s);
70
71
72
73
74
			_sensors.push_back(sensor);
			_baseSensors.push_back(sensor);
		}
	}

75
	virtual ~SensorGroupTemplate() {
76
77
		_sensors.clear();
		_baseSensors.clear();
78
79
	}

80
81
82
83
84
85
	SensorGroupTemplate& operator=(const SensorGroupTemplate& other) {
		SensorGroupInterface::operator=(other);
		_sensors.clear();
		_baseSensors.clear();

		for(auto s : other._sensors) {
86
			S_Ptr sensor = std::make_shared<S>(*s);
87
88
89
90
			_sensors.push_back(sensor);
			_baseSensors.push_back(sensor);
		}

91
92
		_entity = other._entity;

93
94
95
		return *this;
	}

96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
	/**
	 * @brief Initialize the sensor group.
	 *
	 * @details This method must not be overwritten. See execOnInit() if custom
	 *          actions are required during initialization. Initializes
	 *          associated sensors and entity.
	 *
	 * @param io IO service to initialize the timer with.
	 */
    virtual void init(boost::asio::io_service& io) final override {
        if(!_entity) {
            LOG(error) << "No entity set for group " << _groupName << "! Cannot initialize group";
            return;
        }

        SensorGroupInterface::init(io);

        for(auto s : _sensors) {
            s->initSensor(_interval);
        }

        _entity->initEntity(io);

        this->execOnInit();
    }

    /**
     * @brief Start the sensor group (i.e. start collecting data).
     *
     * @details This method must not be overwritten. See execOnStart() if custom
     *          actions are required during startup.
     */
    virtual void start() final override {
        if (_keepRunning) {
            //we have been started already
            LOG(info) << "Sensorgroup " << _groupName << " already running.";
            return;
        }

        this->execOnStart();

        if (_entity) {
            _keepRunning = true;
            _pendingTasks++;
            _timer->async_wait(_entity->getStrand()->wrap(std::bind(&SensorGroupTemplate::readAsync, this)));
            LOG(info) << "Sensorgroup " << _groupName << " started.";
        } else {
            LOG(error) << "No entity set for group " << _groupName << "! Cannot start polling.";
        }
    }

    /**
     * @brief Stop the sensor group (i.e. stop collecting data).
     *
     * @details This method must not be overwritten. See execOnStop() if custom
     *          actions are required during shutdown.
     */
    virtual void stop() final override {
        _keepRunning = false;
        //cancel any outstanding readAsync()
        _timer->cancel();

        this->execOnStop();
        LOG(info) << "Sensorgroup " << _groupName << " stopped.";
    }

    /**
     * @brief Add a sensor to this group.
     *
     * @details Not intended to be overwritten.
     *
     * @param s Shared pointer to the sensor.
     */
	virtual void pushBackSensor(SBasePtr s) final override {
170
171
		//check if dynamic cast returns nullptr
		if (S_Ptr dSensor = std::dynamic_pointer_cast<S>(s)) {
172
173
174
			_sensors.push_back(dSensor);
			_baseSensors.push_back(s);
		} else {
175
			LOG(warning) << "Group " << _groupName << ": Type mismatch when storing sensor! Sensor omitted";
176
177
178
		}
	}

179
180
181
182
183
184
185
186
	/**
     * @brief Retrieve all sensors of this group.
     *
     * @details Not intended to be overwritten.
     *
     * @return A std::vector with shared pointers to all associated sensors.
     */
	virtual std::vector<SBasePtr>& getSensors() final override { return _baseSensors; }
187

188
189
190
191
192
193
194
195
196
197
198
199
200
201
	//TODO only call this printMethod!
	/**
     * @brief Print SensorGroup configuration.
     *
     * @details Always call %SensorGroupTemplate::printConfig() to print
     *          complete configuration of a sensor group. This method takes
     *          care of calling SensorGroupInterface::printConfig() and
     *          derived %printConfig() methods in correct order.
     *
     * @param ll Log severity level to be used from logger.
     */
	virtual void printConfig(LOG_LEVEL ll) override {
	    //print common base attributes
	    SensorGroupInterface::printConfig(ll);
202

203
204
	    //print plugin specific group attributes
	    this->printConfig(ll);
205

206
207
208
209
210
211
	    //print associated sensors
        LOG_VAR(ll) << "            Sensors:";
        for(auto s : _sensors) {
            s->SensorBase::printConfig(ll, lg);
            s->printConfig(ll, lg);
        }
212
213
	}

214
protected:
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229

	/**
     * @brief Asynchronous callback if _timer expires.
     *
     * @details Issues a read() and sets the timer again if _keepRunning is true.
     *          Not intended to be overwritten.
     */
	void readAsync() final override {
	    this->read();
	    if (_timer && _keepRunning) {
	        _timer->expires_at(timestamp2ptime(nextReadingTime()));
	        _pendingTasks++;
	        _timer->async_wait(_entity->getStrand()->wrap(std::bind(&SensorGroupTemplate::readAsync, this)));
	    }
	    _pendingTasks--;
230
231
	}

232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
	///@name Can be overwritten
	///@{
	/**
     * @brief Implement plugin specific actions to initialize a group here.
     *
     * @details If a derived class (i.e. a plugin group) requires further custom
     *          actions for initialization, this should be implemented here.
     *          %initGroup() is appropriately called by this template during
     *          init().
     */
	virtual void execOnInit() { /* do nothing if not overwritten */ };

    /**
     * @brief Implement plugin specific actions to start a group here.
     *
     * @details If a derived class (i.e. a plugin group) requires further custom
     *          actions to start polling data (e.g. open a file descriptor),
     *          this should be implemented here. %startGroup() is appropriately
     *          called by this template during start().
     */
    virtual void execOnStart() { /* do nothing if not overwritten */ };

    /**
     * @brief Implement plugin specific actions to stop a group here.
     *
     * @details If a derived class (i.e. a plugin group) requires further custom
     *          actions to stop polling data (e.g. close a file descriptor),
     *          this should be implemented here. %stopGroup() is appropriately
     *          called by this template during stop().
     */
    virtual void execOnStop() { /* do nothing if not overwritten */ };
    ///@}

	std::vector<S_Ptr>    _sensors; ///< Sensors associated with this group
	std::vector<SBasePtr> _baseSensors; ///< Maintain vector with SensorBase pointers for fast getSensors() implementation
	E_Ptr                 _entity; ///< Entity this group is associated to
};


/**
 * @brief Interface partial template specialization for sensor group
 *        implementations without entities.
 *
 * @details There is a general template for groups with entities. 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 greatly reduces code duplication in derived plugin sensor
 *          groups.
 *
 * @ingroup pusherplugins
 */
template <class S>
class SensorGroupTemplate<S, nullptr_t> : public SensorGroupInterface {
    //the template shall only be instantiated for classes which derive from SensorBase
    static_assert(std::is_base_of<SensorBase, S>::value, "S must derive from SensorBase!");

protected:
    using S_Ptr = std::shared_ptr<S>;

public:
    SensorGroupTemplate(const std::string groupName) :
        SensorGroupInterface(groupName){}

    SensorGroupTemplate(const SensorGroupTemplate& other) :
        SensorGroupInterface(other){

        for(auto s : other._sensors) {
            S_Ptr sensor = std::make_shared<S>(*s);
            _sensors.push_back(sensor);
            _baseSensors.push_back(sensor);
        }
    }

    virtual ~SensorGroupTemplate() {
        _sensors.clear();
        _baseSensors.clear();
    }

    SensorGroupTemplate& operator=(const SensorGroupTemplate& other) {
        SensorGroupInterface::operator=(other);
        _sensors.clear();
        _baseSensors.clear();

        for(auto s : other._sensors) {
            S_Ptr sensor = std::make_shared<S>(*s);
            _sensors.push_back(sensor);
            _baseSensors.push_back(sensor);
        }

        return *this;
    }

    /**
     * @brief Initialize the sensor group.
     *
     * @details This method must not be overwritten. See execOnInit() if custom
     *          actions are required during initialization. Initializes
     *          associated sensors and entity.
     *
     * @param io IO service to initialize the timer with.
     */
    virtual void init(boost::asio::io_service& io) final override {
        SensorGroupInterface::init(io);

        for(auto s : _sensors) {
            s->initSensor(_interval);
        }

        this->execOnInit();
    }

    /**
     * @brief Start the sensor group (i.e. start collecting data).
     *
     * @details This method must not be overwritten. See execOnStart() if custom
     *          actions are required during startup.
     */
    virtual void start() final override {
        if (_keepRunning) {
            //we have been started already
            LOG(info) << "Sensorgroup " << _groupName << " already running.";
            return;
        }

        this->execOnStart();

        _keepRunning = true;
        _pendingTasks++;
        _timer->async_wait(std::bind(&SensorGroupTemplate::readAsync, this));
        LOG(info) << "Sensorgroup " << _groupName << " started.";
    }

    /**
     * @brief Stop the sensor group (i.e. stop collecting data).
     *
     * @details This method must not be overwritten. See execOnStop() if custom
     *          actions are required during shutdown.
     */
    virtual void stop() final override {
        _keepRunning = false;
        //cancel any outstanding readAsync()
        _timer->cancel();

        this->execOnStop();
        LOG(info) << "Sensorgroup " << _groupName << " stopped.";
    }

    /**
     * @brief Add a sensor to this group.
     *
     * @details Not intended to be overwritten.
     *
     * @param s Shared pointer to the sensor.
     */
    virtual void pushBackSensor(SBasePtr s) final override {
        //check if dynamic cast returns nullptr
        if (S_Ptr dSensor = std::dynamic_pointer_cast<S>(s)) {
            _sensors.push_back(dSensor);
            _baseSensors.push_back(s);
        } else {
            LOG(warning) << "Group " << _groupName << ": Type mismatch when storing sensor! Sensor omitted";
        }
    }

    /**
     * @brief Retrieve all sensors of this group.
     *
     * @details Not intended to be overwritten.
     *
     * @return A std::vector with shared pointers to all associated sensors.
     */
    virtual std::vector<SBasePtr>& getSensors() final override { return _baseSensors; }

    //TODO only call this printMethod!
    /**
     * @brief Print SensorGroup configuration.
     *
     * @details Always call %SensorGroupTemplate::printConfig() to print
     *          complete configuration of a sensor group. This method takes
     *          care of calling SensorGroupInterface::printConfig() and
     *          derived %printConfig() methods in correct order.
     *
     * @param ll Log severity level to be used from logger.
     */
    virtual void printConfig(LOG_LEVEL ll) override {
        //print common base attributes
        SensorGroupInterface::printConfig(ll);

        //print plugin specific group attributes
        this->printConfig(ll);

        //print associated sensors
        LOG_VAR(ll) << "            Sensors:";
        for(auto s : _sensors) {
            s->SensorBase::printConfig(ll, lg);
            s->printConfig(ll, lg);
        }
    }

protected:

    /**
     * @brief Asynchronous callback if _timer expires.
     *
     * @details Issues a read() and sets the timer again if _keepRunning is true.
     *          Not intended to be overwritten.
     */
    void readAsync() final override {
        this->read();
        if (_timer && _keepRunning) {
            _timer->expires_at(timestamp2ptime(nextReadingTime()));
            _pendingTasks++;
            _timer->async_wait(std::bind(&SensorGroupTemplate::readAsync, this));
        }
        _pendingTasks--;
    }

    ///@name Can be overwritten
    ///@{
    /**
     * @brief Implement plugin specific actions to initialize a group here.
     *
     * @details If a derived class (i.e. a plugin group) requires further custom
     *          actions for initialization, this should be implemented here.
     *          %initGroup() is appropriately called by this template during
     *          init().
     */
    virtual void execOnInit() { /* do nothing if not overwritten */ };

    /**
     * @brief Implement plugin specific actions to start a group here.
     *
     * @details If a derived class (i.e. a plugin group) requires further custom
     *          actions to start polling data (e.g. open a file descriptor),
     *          this should be implemented here. %startGroup() is appropriately
     *          called by this template during start().
     */
    virtual void execOnStart() { /* do nothing if not overwritten */ };

    /**
     * @brief Implement plugin specific actions to stop a group here.
     *
     * @details If a derived class (i.e. a plugin group) requires further custom
     *          actions to stop polling data (e.g. close a file descriptor),
     *          this should be implemented here. %stopGroup() is appropriately
     *          called by this template during stop().
     */
    virtual void execOnStop() { /* do nothing if not overwritten */ };
    ///@}

    std::vector<S_Ptr>    _sensors; ///< Sensors associated with this group
    std::vector<SBasePtr> _baseSensors; ///< Maintain vector with SensorBase pointers for fast getSensors() implementation
484
485
486
};

#endif /* SENSORGROUPTEMPLATE_H_ */