dcdbpusher.cpp 17.7 KB
Newer Older
1
2
//================================================================================
// Name        : dcdbpusher.cpp
3
// Author      : Michael Ott, Micha Mueller
Micha Müller's avatar
Micha Müller committed
4
// Contact     : info@dcdb.it
5
// Copyright   : Leibniz Supercomputing Centre
6
// Description : Main function for the DCDB MQTT Pusher.
7
8
9
10
//================================================================================

//================================================================================
// This file is part of DCDB (DataCenter DataBase)
11
// Copyright (C) 2011-2019 Leibniz Supercomputing Centre
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//
// 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.
//================================================================================

28
29
30
/**
 * @defgroup pusher Pusher
 *
31
32
33
34
35
 * @brief Data harvester for DCDB.
 *
 * @details Pusher is the DCDB building block responsible for gathering data from
 * 	        hard-/software and pushing the values to the collect agent. The data
 * 	        collection capabilities of pusher stem from its plugins.
36
37
38
39
40
41
42
43
44
45
 */

/**
 * @file dcdbpusher.cpp
 *
 * @brief Main function for the DCDB MQTT Pusher.
 *
 * @ingroup pusher
 */

46
47
#include <dcdbdaemon.h>
#include <functional>
48
#include <string>
49
#include <vector>
50

51
52
#include "Configuration.h"
#include "MQTTPusher.h"
53
#include "PluginManager.h"
54
#include "RestAPI.h"
55
#include "version.h"
56
#include "abrt.h"
57
58

#include <boost/asio.hpp>
59
#include <boost/foreach.hpp>
60
61
#include <boost/thread/thread.hpp>

62
63
#include <boost/log/expressions.hpp>
#include <boost/log/support/date_time.hpp>
64
65
66
67
#include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/utility/setup/file.hpp>
68

69
70
using namespace std;

71
72
73
74
75
76
Configuration *  _configuration;
MQTTPusher *     _mqttPusher;
PluginManager *  _pluginManager;
RestAPI *        _httpsServer;
OperatorManager *_operatorManager;
QueryEngine &    _queryEngine = QueryEngine::getInstance();
77

78
boost::shared_ptr<boost::asio::io_service::work> keepAliveWork;
79

80
bool sensorQueryCallback(const string &name, const uint64_t startTs, const uint64_t endTs, std::vector<reading_t> &buffer, const bool rel) {
Alessio Netti's avatar
Alessio Netti committed
81
	// Returning NULL if the query engine is being updated
82
83
84
	if (_queryEngine.updating.load())
		return false;
	bool found = false;
85
86
	++_queryEngine.access;
	shared_ptr<map<string, SBasePtr>> sensorMap = _queryEngine.getSensorMap();
87
88

	if (sensorMap != nullptr && sensorMap->count(name) > 0) {
89
		SBasePtr sensor = sensorMap->at(name);
90
		found = sensor->isInit() ? sensor->getCache()->getView(startTs, endTs, buffer, rel) : false;
91
	}
92
	--_queryEngine.access;
93
	return found;
94
95
}

96
97
98
99
100
101
102
103
104
105
bool sensorGroupQueryCallback(const std::vector<string> &names, const uint64_t startTs, const uint64_t endTs, std::vector<reading_t> &buffer, const bool rel) {
	// Returning NULL if the query engine is being updated
	if (_queryEngine.updating.load())
		return false;
	bool outcome = false;
	for(const auto& name : names)
		outcome = outcome || sensorQueryCallback(name, startTs, endTs, buffer, rel);
	return outcome;
}

106
bool metadataQueryCallback(const string &name, SensorMetadata &buffer) {
107
	// Returning NULL if the query engine is being updated
108
109
110
	if (_queryEngine.updating.load())
		return false;
	bool found = false;
111
112
113
	++_queryEngine.access;
	shared_ptr<map<string, SBasePtr>> sensorMap = _queryEngine.getSensorMap();

114
	if (sensorMap != nullptr && sensorMap->count(name) > 0) {
115
		SBasePtr sensor = sensorMap->at(name);
116
		if (!sensor->getMetadata()) {
117
118
119
120
121
122
123
124
125
126
			found = false;
		} else {
			found = true;
			buffer = *sensor->getMetadata();
		}
	}
	--_queryEngine.access;
	return found;
}

Alessio Netti's avatar
Alessio Netti committed
127
void sigHandler(int sig) {
128
	boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;
129
	if (sig == SIGINT)
Alessio Netti's avatar
Alessio Netti committed
130
		LOG(fatal) << "Received SIGINT";
131
	else if (sig == SIGTERM)
Alessio Netti's avatar
Alessio Netti committed
132
		LOG(fatal) << "Received SIGTERM";
133

134
135
	//Stop data analytics plugins and operators
	_operatorManager->stop();
136

137
138
	//Stop all sensors
	LOG(info) << "Stopping sensors...";
139
	_pluginManager->stopPlugin();
140

141
142
	//Stop io service by killing keepAliveWork
	keepAliveWork.reset();
143
144
145
146

	//Stop MQTTPusher
	LOG(info) << "Flushing MQTT queues...";
	_mqttPusher->stop();
147
148
}

149
150
void printSyntax() {
	/*
151
152
153
154
                       1         2         3         4         5         6         7         8
             012345678901234567890123456789012345678901234567890123456789012345678901234567890
*/
	cout << "Usage:" << endl;
155
	cout << "  dcdbpusher [-d] [-x] [-a] [-b<host>] [-m<string>] [-w<path>] [-v<level>] <config>" << endl;
156
157
158
159
	cout << "  dcdbpusher -h" << endl;
	cout << endl;

	cout << "Options:" << endl;
160
	cout << "  -b <host>       MQTT broker                  [default: " << DEFAULT_BROKERHOST << ":" << DEFAULT_BROKERPORT << "]" << endl;
161
	cout << "  -m <string>     MQTT topic prefix            [default: none]" << endl;
162
163
	cout << "  -w <path>       Writable temp dir            [default: " << DEFAULT_TEMPDIR << "]" << endl;
	cout << "  -v <level>      Set verbosity of output      [default: " << DEFAULT_LOGLEVEL << "]" << endl
164
	     << "                  Can be a number between 5 (all) and 0 (fatal)." << endl;
165
166
	cout << endl;
	cout << "  -d              Daemonize" << endl;
167
	cout << "  -x              Parse and print the config but do not actually start dcdbpusher" << endl;
168
	cout << "  -a			   Enable sensor auto-publish" << endl;
169
170
171
172
	cout << "  -h              This help page" << endl;
	cout << endl;
}

173
174
175
int main(int argc, char **argv) {
	cout << "dcdbpusher " << VERSION << endl
	     << endl;
176
	boost::asio::io_service io;
177
	boost::thread_group     threads;
178

179
	if (argc <= 1) {
180
		cout << "Please specify a path to the config-directory or a config-file" << endl
181
		     << endl;
182
		printSyntax();
183
184
185
		return 1;
	}

186
	//define allowed command-line options once
187
	const char opts[] = "b:p:m:v:w:dxah";
188

189
190
191
	//check if help flag specified
	char c;
	while ((c = getopt(argc, argv, opts)) != -1) {
192
		switch (c) {
193
194
195
196
197
198
199
200
			case 'h':
				printSyntax();
				return 1;
			default:
				//do nothing (other options are read later on)
				break;
		}
	}
201
	
202
	//init LOGGING
Alessio Netti's avatar
Alessio Netti committed
203
	initLogging();
204
	
205
	//set up logger to command line
Alessio Netti's avatar
Alessio Netti committed
206
	auto cmdSink = setupCmdLogger();
207
	
208
209
	//get logger instance
	boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;
210
	//finished logging startup for the moment (file log added later)
211

212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
	try {
		_configuration = new Configuration(argv[argc - 1], "dcdbpusher.conf");
		
		//Read global variables from config file
		_configuration->readConfig();
		
		//plugin and restAPI settings are actually part of globalSettings
		//use the references as shortcut, so that we do not have to prefix with 'globalSettings.' all the time
		Configuration &      globalSettings = *_configuration;
		pluginSettings_t &   pluginSettings = _configuration->pluginSettings;
		serverSettings_t &   restAPISettings = _configuration->restAPISettings;
		analyticsSettings_t &analyticsSettings = _configuration->analyticsSettings;
		
		//reset getopt()
		optind = 1;
		//read in options (overwrite dcdbpusher.conf settings if necessary)
		while ((c = getopt(argc, argv, opts)) != -1) {
			switch (c) {
				case 'a':
					pluginSettings.autoPublish = true;
					break;
				case 'b':
					globalSettings.brokerHost = parseNetworkHost(optarg);
235
					globalSettings.brokerPort = parseNetworkPort(optarg) == "" ? DEFAULT_BROKERPORT : stoi(parseNetworkPort(optarg));
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
					break;
				case 'm':
					pluginSettings.mqttPrefix = optarg;
					break;
				case 'v':
					globalSettings.logLevelCmd = stoi(optarg);
					break;
				case 'd':
					globalSettings.daemonize = 1;
					break;
				case 'x':
					globalSettings.validateConfig = true;
					break;
				case 'w':
					pluginSettings.tempdir = optarg;
					if (pluginSettings.tempdir[pluginSettings.tempdir.length() - 1] != '/') {
						pluginSettings.tempdir.append("/");
					}
					break;
				case 'h':
					printSyntax();
					return 1;
				default:
					if (c != '?')
						cerr << "Unknown parameter: " << c << endl;
					return 1;
			}
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
		
		//we now should know where the writable tempdir is
		//set up logger to file
		if (globalSettings.logLevelFile >= 0) {
			auto fileSink = setupFileLogger(pluginSettings.tempdir, std::string("dcdbpusher"));
			fileSink->set_filter(boost::log::trivial::severity >= translateLogLevel(globalSettings.logLevelFile));
		}
		
		//severity level may be overwritten (per option or config-file) --> set it according to globalSettings
		if (globalSettings.logLevelCmd >= 0) {
			cmdSink->set_filter(boost::log::trivial::severity >= translateLogLevel(globalSettings.logLevelCmd));
		}
		
		LOG(info) << "Logging setup complete";
		
		_pluginManager = new PluginManager(pluginSettings);
		//Read in rest of configuration. Also creates all sensors
		if (!_configuration->readPlugins(*_pluginManager)) {
			LOG(fatal) << "Failed to read configuration!";
			return 1;
		}
		
		_operatorManager = new OperatorManager();
		// Preparing the SensorNavigator
		if (_operatorManager->probe(globalSettings.cfgFilePath, globalSettings.cfgFileName)) {
			std::shared_ptr<SensorNavigator> navigator = std::make_shared<SensorNavigator>();
			vector<std::string>              topics;
			for (const auto &p : _pluginManager->getPlugins())
				for (const auto &g : p.configurator->getSensorGroups()) {
					for (const auto &s : g->acquireSensors())
						topics.push_back(s->getMqtt());
					g->releaseSensors();
				}
			try {
				navigator->setFilter(analyticsSettings.filter);
				navigator->buildTree(analyticsSettings.hierarchy, &topics);
				topics.clear();
				LOG(info) << "Built a sensor hierarchy tree of size " << navigator->getTreeSize() << " and depth " << navigator->getTreeDepth() << ".";
			} catch (const std::invalid_argument &e) {
				navigator->clearTree();
				LOG(error) << e.what();
				LOG(error) << "Failed to build sensor hierarchy tree!";
306
			}
307
			_queryEngine.setNavigator(navigator);
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
		
		_queryEngine.setFilter(analyticsSettings.filter);
		_queryEngine.setJobFilter(analyticsSettings.jobFilter);
		_queryEngine.setJobMatch(analyticsSettings.jobMatch);
		_queryEngine.setSensorHierarchy(analyticsSettings.hierarchy);
		_queryEngine.setQueryCallback(sensorQueryCallback);
		_queryEngine.setGroupQueryCallback(sensorGroupQueryCallback);
		_queryEngine.setMetadataQueryCallback(metadataQueryCallback);
		
		if (!_operatorManager->load(globalSettings.cfgFilePath, globalSettings.cfgFileName, pluginSettings)) {
			LOG(fatal) << "Failed to load data analytics manager!";
			return 1;
		} else if (!_operatorManager->getPlugins().empty()) {
			// Preparing the sensor map used for the QueryEngine
			std::shared_ptr<std::map<std::string, SBasePtr>> sensorMap = std::make_shared<std::map<std::string, SBasePtr>>();
			
			for (const auto &p : _pluginManager->getPlugins())
				for (const auto &g : p.configurator->getSensorGroups()) {
					for (const auto &s : g->acquireSensors())
						sensorMap->insert(std::make_pair(s->getName(), s));
					g->releaseSensors();
				}
			
			for (auto &p : _operatorManager->getPlugins()) {
				for (const auto &op : p.configurator->getOperators())
					if (op->getStreaming()) {
						for (const auto &u : op->getUnits())
							for (const auto &o : u->getBaseOutputs())
								sensorMap->insert(std::make_pair(o->getName(), o));
						op->releaseUnits();
					}
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
			_queryEngine.setSensorMap(sensorMap);
		}
		
		//print configuration to give some feedback
		//config of plugins is only printed if the config shall be validated or to debug level otherwise
		LOG_LEVEL vLogLevel = LOG_LEVEL::debug;
		if (globalSettings.validateConfig) {
			vLogLevel = boost::log::trivial::info;
		}
		LOG_VAR(vLogLevel) << "-----  Configuration  -----";
		
		//print global settings in either case
		LOG(info) << "Global Settings:";
		LOG(info) << "    Broker:             " << globalSettings.brokerHost << ":" << globalSettings.brokerPort;
		LOG(info) << "    Threads:            " << globalSettings.threads;
		LOG(info) << "    Daemonize:          " << (globalSettings.daemonize ? "Enabled" : "Disabled");
		LOG(info) << "    MaxMsgNum:          " << globalSettings.maxMsgNum;
		LOG(info) << "    MaxInflightMsgNum:  " << globalSettings.maxInflightMsgNum;
		LOG(info) << "    MaxQueuedMsgNum:    " << globalSettings.maxQueuedMsgNum;
		LOG(info) << "    MQTT-QoS:           " << globalSettings.qosLevel;
		LOG(info) << "    MQTT-prefix:        " << pluginSettings.mqttPrefix;
		LOG(info) << "    Auto-publish:       " << (pluginSettings.autoPublish ? "Enabled" : "Disabled");
		LOG(info) << "    Write-Dir:          " << pluginSettings.tempdir;
		LOG(info) << "    CacheInterval:      " << pluginSettings.cacheInterval / 1000 << " [s]";
		if (globalSettings.validateConfig) {
			LOG(info) << "    Only validating config files.";
		} else {
			LOG(info) << "    ValidateConfig:     Disabled";
		}
		LOG(info) << "Analytics Settings:";
		LOG(info) << "    Hierarchy:          " << (analyticsSettings.hierarchy != "" ? analyticsSettings.hierarchy : "none");
		LOG(info) << "    Filter:             " << (analyticsSettings.filter != "" ? analyticsSettings.filter : "none");
		LOG(info) << "    Job Filter:         " << (analyticsSettings.jobFilter != "" ? analyticsSettings.jobFilter : "none");
		LOG(info) << "    Job Match:          " << (analyticsSettings.jobMatch != "" ? analyticsSettings.jobMatch : "none");
		if (restAPISettings.enabled) {
			LOG(info) << "RestAPI Settings:";
			LOG(info) << "    REST Server: " << restAPISettings.host << ":" << restAPISettings.port;
			LOG(info) << "    Certificate: " << restAPISettings.certificate;
			LOG(info) << "    Private key file: " << restAPISettings.privateKey;
		}
		LOG_VAR(vLogLevel) << "-----  Sampling Configuration  -----";
		for (auto &p : _pluginManager->getPlugins()) {
			LOG_VAR(vLogLevel) << "Sampling Plugin \"" << p.id << "\"";
			p.configurator->printConfig(vLogLevel);
		}
		
		LOG_VAR(vLogLevel) << "-----  Analytics Configuration  -----";
388
		for (auto &p : _operatorManager->getPlugins()) {
389
390
			LOG_VAR(vLogLevel) << "Operator Plugin \"" << p.id << "\"";
			p.configurator->printConfig(vLogLevel);
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
484
485
486
487
488
489
490
491
492
		
		LOG_VAR(vLogLevel) << "-----  End Configuration  -----";
		
		//MQTTPusher and Https server get their own threads
		_mqttPusher = new MQTTPusher(globalSettings.brokerPort, globalSettings.brokerHost, pluginSettings.autoPublish, globalSettings.qosLevel,
					     _pluginManager->getPlugins(), _operatorManager->getPlugins(), globalSettings.maxMsgNum, globalSettings.maxInflightMsgNum, globalSettings.maxQueuedMsgNum);
		if (restAPISettings.enabled) {
			_httpsServer = new RestAPI(restAPISettings, _pluginManager, _mqttPusher, _operatorManager, io);
			_configuration->readRestAPIUsers(_httpsServer);
		}
		if (globalSettings.validateConfig) {
			return 0;
		}
		
		//Init all sensors
		LOG(info) << "Init sensors...";
		_pluginManager->initPlugin(io);
		
		//Start all sensors
		LOG(info) << "Starting sensors...";
		_pluginManager->startPlugin();
		
		if (!_queryEngine.updating.is_lock_free())
			LOG(warning) << "This machine does not support lock-free atomics. Performance may be degraded.";
		
		LOG(info) << "Init operators...";
		_operatorManager->init(io);
		
		LOG(info) << "Starting operators...";
		_operatorManager->start();
		
		LOG(info) << "Sensors started!";
		
		if (globalSettings.daemonize) {
			//boost.log does not support forking officially.
			//however, just don't touch the sinks after daemonizing and it should work nonetheless
			LOG(info) << "Detaching...";
			
			cmdSink->flush();
			boost::log::core::get()->remove_sink(cmdSink);
			cmdSink.reset();
			
			//daemonize
			dcdbdaemon();
			
			LOG(info) << "Now detached";
		}
		
		LOG(info) << "Creating threads...";
		
		//dummy to keep io service alive even if no tasks remain (e.g. because all sensors have been stopped over REST API)
		keepAliveWork = boost::make_shared<boost::asio::io_service::work>(io);
		
		//Create pool of threads which handle the sensors
		for (size_t i = 0; i < globalSettings.threads; i++) {
			threads.create_thread(bind(static_cast<size_t (boost::asio::io_service::*)()>(&boost::asio::io_service::run), &io));
		}
		
		boost::thread mqttThread(bind(&MQTTPusher::push, _mqttPusher));
		
		LOG(info) << "Threads created!";
		
		if (restAPISettings.enabled) {
			LOG(info) << "Starting RestAPI Https Server...";
			_httpsServer->start();
		}
		
		LOG(info) << "Registering signal handlers...";
		signal(SIGINT, sigHandler);  //Handle Strg+C
		signal(SIGTERM, sigHandler); //Handle termination
		LOG(info) << "Signal handlers registered!";
		
		LOG(info) << "Cleaning up...";
		bool restAPIEnabled = restAPISettings.enabled;
		delete _configuration;
		
		LOG(info) << "Setup complete!";
		
		LOG(trace) << "Running...";
		
		//Run until Strg+C
		threads.join_all();
		
		//will only continue if interrupted by SIGINT and threads were stopped
		
		mqttThread.join();
		LOG(info) << "MQTTPusher stopped.";
		
		if (restAPIEnabled) {
			//Stop https server
			LOG(info) << "Stopping REST API Server...";
			_httpsServer->stop();
			delete _httpsServer;
		}
		
		LOG(info) << "Tearing down objects...";
		_queryEngine.setNavigator(nullptr);
		_queryEngine.setSensorMap(nullptr);
		delete _mqttPusher;
		delete _operatorManager;
		delete _pluginManager;
493
	}
494
495
496
	catch (const std::runtime_error& e) {
		LOG(fatal) <<  e.what();
		return EXIT_FAILURE;
497
	}
498
499
500
	catch (const exception& e) {
		LOG(fatal) << "Exception: " << e.what();
		abrt(EXIT_FAILURE, INTERR);
501
	}
502
	
Micha Mueller's avatar
Micha Mueller committed
503
	LOG(info) << "Exiting...Goodbye!";
504
505
	return 0;
}