SensorGroupTemplate.h 15.7 KB
Newer Older
1
2
3
//================================================================================
// Name        : SensorGroupTemplate.h
// Author      : Micha Mueller
Micha Müller's avatar
Micha Müller committed
4
// Contact     : info@dcdb.it
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Copyright   : Leibniz Supercomputing Centre
// Description : Interface template for 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.
//================================================================================
27
28
29
30

#ifndef SENSORGROUPTEMPLATE_H_
#define SENSORGROUPTEMPLATE_H_

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

34
35
36
#include "timestamp.h"

#include <vector>
37
#include <memory>
38

39
/**
40
41
42
 * @brief Interface template for sensor group implementations with entities.
 *
 * @details There is a partial template specialization for E = nullptr_t, i.e.
43
44
45
46
47
 *          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.
48
49
50
51
 *          Internal usage of _baseSensors is not synchronized via
 *          acquireSensors()/releaseSensors() as it is only accessed (e.g. in
 *          (de-)constructor) when no other caller is expected to access
 *          _baseSensors.
52
53
54
 *
 * @ingroup pusherplugins
 */
55
template <class S, class E = nullptr_t>
56
class SensorGroupTemplate : public SensorGroupInterface {
57
	//the template shall only be instantiated for classes which derive from SensorBase and EntityInterface respectively
58
	static_assert(std::is_base_of<SensorBase, S>::value, "S must derive from SensorBase!");
59
	static_assert(std::is_base_of<EntityInterface, E>::value, "E must derive from EntityInterface!");
60

61
62
63
protected:
	using S_Ptr = std::shared_ptr<S>;

64
65
public:
	SensorGroupTemplate(const std::string groupName) :
66
67
		SensorGroupInterface(groupName),
		_entity(nullptr) {}
68

69
	SensorGroupTemplate(const SensorGroupTemplate& other) :
70
71
72
		SensorGroupInterface(other),
		_entity(other._entity) {

73
		for(auto s : other._sensors) {
74
			S_Ptr sensor = std::make_shared<S>(*s);
75
76
77
78
79
			_sensors.push_back(sensor);
			_baseSensors.push_back(sensor);
		}
	}

80
	virtual ~SensorGroupTemplate() {
81
82
83
84
	    if(_keepRunning) {
	        stop();
	    }

85
86
		_sensors.clear();
		_baseSensors.clear();
87
88
	}

89
90
91
92
93
94
	SensorGroupTemplate& operator=(const SensorGroupTemplate& other) {
		SensorGroupInterface::operator=(other);
		_sensors.clear();
		_baseSensors.clear();

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

100
101
		_entity = other._entity;

102
103
104
		return *this;
	}

105
106
107
	void setEntity(E* entity) { _entity = entity; }
	E* const getEntity() const { return _entity; }

108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
	/**
	 * @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);
        }

129
        _entity->init(io);
130
131
132
133

        this->execOnInit();
    }

134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
    /**
     * @brief Does a busy wait until all dispatched handlers are finished
     *        (_pendingTasks == 0).
     *
     * @details If the wait takes longer than a reasonable amount of time we
     *          return anyway, to not block termination of dcdbpusher.
     */
    virtual void wait() final override {
        uint64_t sleepms=10, i=0;
        uint64_t timeout = _interval<10000 ? 10000 : _interval;

        while(sleepms*i++ < timeout) {
            if (_pendingTasks)
                std::this_thread::sleep_for(std::chrono::milliseconds(sleepms));
            else {
                this->execOnStop();
                LOG(info) << "Sensorgroup " << _groupName << " stopped.";
                return;
            }
        }

        LOG(warning) << "Group " << _groupName << " will not finish! Skipping it";
    }

158
159
160
161
162
163
164
165
166
167
168
169
170
    /**
     * @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;
        }

171
172
173
174
        if (!this->execOnStart()) {
            LOG(error) << "Sensorgroup " << _groupName << ": Startup failed.";
            return;
        }
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192

        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 {
193
        if (!_keepRunning) {
194
            LOG(debug) << "Sensorgroup " << _groupName << " already stopped.";
195
196
197
            return;
        }

198
199
200
201
202
203
204
205
206
207
208
209
210
        _keepRunning = false;
        //cancel any outstanding readAsync()
        _timer->cancel();
    }

    /**
     * @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 {
211
212
		//check if dynamic cast returns nullptr
		if (S_Ptr dSensor = std::dynamic_pointer_cast<S>(s)) {
213
214
215
			_sensors.push_back(dSensor);
			_baseSensors.push_back(s);
		} else {
216
			LOG(warning) << "Group " << _groupName << ": Type mismatch when storing sensor! Sensor omitted";
217
218
219
		}
	}

220
221
222
223
224
225
226
227
228
229
	/**
     * @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.
     */
230
	virtual void printConfig(LOG_LEVEL ll) final override {
231
232
	    //print common base attributes
	    SensorGroupInterface::printConfig(ll);
233

234
	    //print plugin specific group attributes
235
	    this->printGroupConfig(ll);
236

237
        if (_entity) {
238
            LOG_VAR(ll) << "            Entity " << _entity->getName();
239
240
241
242
        } else {
            LOG_VAR(ll) << "            No entity set!";
        }

243
244
245
246
247
248
	    //print associated sensors
        LOG_VAR(ll) << "            Sensors:";
        for(auto s : _sensors) {
            s->SensorBase::printConfig(ll, lg);
            s->printConfig(ll, lg);
        }
249
250
	}

251
protected:
252
253
254
255
256
257

	/**
     * @brief Asynchronous callback if _timer expires.
     *
     * @details Issues a read() and sets the timer again if _keepRunning is true.
     */
258
	void readAsync() {
259
260
261
262
263
264
265
	    this->read();
	    if (_timer && _keepRunning) {
	        _timer->expires_at(timestamp2ptime(nextReadingTime()));
	        _pendingTasks++;
	        _timer->async_wait(_entity->getStrand()->wrap(std::bind(&SensorGroupTemplate::readAsync, this)));
	    }
	    _pendingTasks--;
266
267
	}

268
	std::vector<S_Ptr>    _sensors; ///< Store pointers to actual sensor objects in addition to general sensor base pointers
269
	E*                    _entity; ///< Entity this group is associated to
270
271
};

272
273
274
275
276
277

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


278
279
280
281
/**
 * @brief Interface partial template specialization for sensor group
 *        implementations without entities.
 *
282
283
284
285
286
 * @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.
287
288
289
290
 *          Internal usage of _baseSensors is not synchronized via
 *          acquireSensors()/releaseSensors() as it is only accessed (e.g. in
 *          (de-)constructor) when no other caller is expected to access
 *          _baseSensors.
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
 *
 * @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() {
317
318
319
320
        if(_keepRunning) {
            stop();
        }

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

358
359
360
361
362
363
364
365
366
    /**
     * @brief Does a busy wait until all dispatched handlers are finished
     *        (_pendingTasks == 0).
     *
     * @details If the wait takes longer than a reasonable amount of time we
     *          return anyway, to not block termination of dcdbpusher.
     */
    virtual void wait() final override {
        uint64_t sleepms=10, i=0;
367
        uint64_t timeout = _interval<10000 ? 30000 : _interval*3;
368
369
370
371
372
373
374
375
376
377
378
379
380
381

        while(sleepms*i++ < timeout) {
            if (_pendingTasks)
                std::this_thread::sleep_for(std::chrono::milliseconds(sleepms));
            else {
                this->execOnStop();
                LOG(info) << "Sensorgroup " << _groupName << " stopped.";
                return;
            }
        }

        LOG(warning) << "Group " << _groupName << " will not finish! Skipping it";
    }

382
383
384
385
386
387
388
389
390
391
392
393
394
    /**
     * @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;
        }

395
396
397
398
        if (!this->execOnStart()) {
            LOG(error) << "Sensorgroup " << _groupName << ": Startup failed.";
            return;
        }
399
400
401
402
403
404
405
406
407
408
409
410
411
412

        _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 {
413
        if (!_keepRunning) {
414
            LOG(debug) << "Sensorgroup " << _groupName << " already stopped.";
415
416
417
            return;
        }

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
        _keepRunning = false;
        //cancel any outstanding readAsync()
        _timer->cancel();
    }

    /**
     * @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 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.
     */
450
    virtual void printConfig(LOG_LEVEL ll) final override {
451
452
453
454
        //print common base attributes
        SensorGroupInterface::printConfig(ll);

        //print plugin specific group attributes
455
        this->printGroupConfig(ll);
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471

        //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.
     */
472
    void readAsync() {
473
474
475
476
477
478
479
480
481
        this->read();
        if (_timer && _keepRunning) {
            _timer->expires_at(timestamp2ptime(nextReadingTime()));
            _pendingTasks++;
            _timer->async_wait(std::bind(&SensorGroupTemplate::readAsync, this));
        }
        _pendingTasks--;
    }

482
    std::vector<S_Ptr>    _sensors; ///< Store pointers to actual sensor objects in addition to general sensor base pointers
483
484
485
};

#endif /* SENSORGROUPTEMPLATE_H_ */