SensorGroupTemplate.h 17.3 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
//TODO cross reference partial template specialization in doxygen docs
39
/**
40
41
42
43
44
45
46
 * @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.
47
48
49
 *
 * @ingroup pusherplugins
 */
50
template <class S, class E = nullptr_t>
51
class SensorGroupTemplate : public SensorGroupInterface {
52
	//the template shall only be instantiated for classes which derive from SensorBase and EntityInterface respectively
53
	static_assert(std::is_base_of<SensorBase, S>::value, "S must derive from SensorBase!");
54
	static_assert(std::is_base_of<EntityInterface, E>::value, "E must derive from EntityInterface!");
55

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

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
78
79
	    if(_keepRunning) {
	        stop();
	    }

80
81
		_sensors.clear();
		_baseSensors.clear();
82
83
	}

84
85
86
87
88
89
	SensorGroupTemplate& operator=(const SensorGroupTemplate& other) {
		SensorGroupInterface::operator=(other);
		_sensors.clear();
		_baseSensors.clear();

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

95
96
		_entity = other._entity;

97
98
99
		return *this;
	}

100
101
102
	void setEntity(E* entity) { _entity = entity; }
	E* const getEntity() const { return _entity; }

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
	/**
	 * @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;
        }

142
143
144
145
        if (!this->execOnStart()) {
            LOG(error) << "Sensorgroup " << _groupName << ": Startup failed.";
            return;
        }
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163

        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 {
164
165
166
167
168
        if (!_keepRunning) {
            LOG(info) << "Sensorgroup " << _groupName << " already stopped.";
            return;
        }

169
170
171
        _keepRunning = false;
        //cancel any outstanding readAsync()
        _timer->cancel();
172
        wait();
173
174
175
176
177
178
179
180
181
182
183
184
185

        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 {
186
187
		//check if dynamic cast returns nullptr
		if (S_Ptr dSensor = std::dynamic_pointer_cast<S>(s)) {
188
189
190
			_sensors.push_back(dSensor);
			_baseSensors.push_back(s);
		} else {
191
			LOG(warning) << "Group " << _groupName << ": Type mismatch when storing sensor! Sensor omitted";
192
193
194
		}
	}

195
196
197
198
199
200
201
202
	/**
     * @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; }
203

204
	//TODO only call this printMethod!
205
	//TODO refactor: use printGroupConfig in derived classes
206
207
208
209
210
211
212
213
214
215
216
217
218
	/**
     * @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);
219

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

223
224
225
226
227
228
        if (_entity) {
            LOG_VAR(ll) << "            Entity " << _entity->getEntityName();
        } else {
            LOG_VAR(ll) << "            No entity set!";
        }

229
230
231
232
233
234
	    //print associated sensors
        LOG_VAR(ll) << "            Sensors:";
        for(auto s : _sensors) {
            s->SensorBase::printConfig(ll, lg);
            s->printConfig(ll, lg);
        }
235
236
	}

237
protected:
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252

	/**
     * @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--;
253
254
	}

255
	//TODO move common logic to interface
256
257
258
259
260
261
262
263
264
265
	///@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().
     */
266
	virtual void execOnInit() { /* do nothing if not overwritten */ }
267
268
269
270
271
272
273
274

    /**
     * @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().
275
276
     *
     * @return True on success, false otherwise.
277
     */
278
    virtual bool execOnStart() { return true; }
279
280
281
282
283
284
285
286
287

    /**
     * @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().
     */
288
    virtual void execOnStop() { /* do nothing if not overwritten */ }
289
290
291
292
    ///@}

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

296
//TODO cross reference general template in doxygen docs
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
/**
 * @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() {
332
333
334
335
        if(_keepRunning) {
            stop();
        }

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
        _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;
        }

386
387
388
389
        if (!this->execOnStart()) {
            LOG(error) << "Sensorgroup " << _groupName << ": Startup failed.";
            return;
        }
390
391
392
393
394
395
396
397
398
399
400
401
402
403

        _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 {
404
405
406
407
408
        if (!_keepRunning) {
            LOG(info) << "Sensorgroup " << _groupName << " already stopped.";
            return;
        }

409
410
411
        _keepRunning = false;
        //cancel any outstanding readAsync()
        _timer->cancel();
412
        wait();
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497

        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().
     */
498
    virtual void execOnInit() { /* do nothing if not overwritten */ }
499
500
501
502
503
504
505
506

    /**
     * @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().
507
508
     *
     * @return True on success, false otherwise.
509
     */
510
    virtual bool execOnStart() { return true; }
511
512
513
514
515
516
517
518
519

    /**
     * @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().
     */
520
    virtual void execOnStop() { /* do nothing if not overwritten */ }
521
522
523
524
    ///@}

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

#endif /* SENSORGROUPTEMPLATE_H_ */