SensorGroupTemplate.h 17.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        : 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
 * @brief Interface template for sensor group implementations with entities.
 *
 * @details There is a partial template specialization for E = nullptr_t, i.e.
42
43
44
45
46
 *          for groups without entities, see SensorGroupTemplate<S, nullptr_t>.
 *          Common code has to be duplicated and maintained twice here and in
 *          the SensorGroupTemplate<S, nullptr_t>. 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
	/**
	 * @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);
        }

124
        _entity->init(io);
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141

        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
205
206
207
208
209
210
211
212
213
	/**
     * @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.
     */
214
	virtual void printConfig(LOG_LEVEL ll) final override {
215
216
	    //print common base attributes
	    SensorGroupInterface::printConfig(ll);
217

218
	    //print plugin specific group attributes
219
	    this->printGroupConfig(ll);
220

221
        if (_entity) {
222
            LOG_VAR(ll) << "            Entity " << _entity->getName();
223
224
225
226
        } else {
            LOG_VAR(ll) << "            No entity set!";
        }

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

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

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

253
	//TODO move common logic to interface
254
255
256
257
258
259
260
	///@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.
261
     *          %execOnInit() is appropriately called by this template during
262
263
     *          init().
     */
264
	virtual void execOnInit() { /* do nothing if not overwritten */ }
265
266
267
268
269
270

    /**
     * @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),
271
     *          this should be implemented here. %execOnStart() is appropriately
272
     *          called by this template during start().
273
274
     *
     * @return True on success, false otherwise.
275
     */
276
    virtual bool execOnStart() { return true; }
277
278
279
280
281
282

    /**
     * @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),
283
     *          this should be implemented here. %execOnStop() is appropriately
284
285
     *          called by this template during stop().
     */
286
    virtual void execOnStop() { /* do nothing if not overwritten */ }
287
288
289
290
    ///@}

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

294
295
296
297
298
299

////////////////////////////////////////////////////////////////////////////////
// Partial template specialization for E = nullptr_t
////////////////////////////////////////////////////////////////////////////////


300
301
302
303
/**
 * @brief Interface partial template specialization for sensor group
 *        implementations without entities.
 *
304
305
306
307
308
 * @details There is a general template for groups with entities, see
 *          SensorGroupTemplate. Common code has to be duplicated and maintained
 *          twice here and in SensorGroupTemplate. However, having two templates
 *          for cases with and without entities greatly reduces code duplication
 *          in derived plugin sensor groups.
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
 *
 * @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() {
335
336
337
338
        if(_keepRunning) {
            stop();
        }

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

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

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

412
413
414
        _keepRunning = false;
        //cancel any outstanding readAsync()
        _timer->cancel();
415
        wait();
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

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

    /**
     * @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.
     */
457
    virtual void printConfig(LOG_LEVEL ll) final override {
458
459
460
461
        //print common base attributes
        SensorGroupInterface::printConfig(ll);

        //print plugin specific group attributes
462
        this->printGroupConfig(ll);
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
498
499

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

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

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

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

#endif /* SENSORGROUPTEMPLATE_H_ */