dcdbpusher.cpp 18.2 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;

Alessio Netti's avatar
Alessio Netti committed
71
int retCode = 0;
72
73
74
75
76
77
Configuration *  _configuration;
MQTTPusher *     _mqttPusher;
PluginManager *  _pluginManager;
RestAPI *        _httpsServer;
OperatorManager *_operatorManager;
QueryEngine &    _queryEngine = QueryEngine::getInstance();
78

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

81
bool sensorQueryCallback(const string &name, const uint64_t startTs, const uint64_t endTs, std::vector<reading_t> &buffer, const bool rel, const uint64_t tol) {
Alessio Netti's avatar
Alessio Netti committed
82
	// Returning NULL if the query engine is being updated
83
84
85
	if (_queryEngine.updating.load())
		return false;
	bool found = false;
86
87
	++_queryEngine.access;
	shared_ptr<map<string, SBasePtr>> sensorMap = _queryEngine.getSensorMap();
Alessio Netti's avatar
Alessio Netti committed
88
	
89
	if (sensorMap != nullptr && sensorMap->count(name) > 0) {
90
		SBasePtr sensor = sensorMap->at(name);
91
		found = sensor->isInit() ? sensor->getCache()->getView(startTs, endTs, buffer, rel, tol) : false;
92
	}
93
	--_queryEngine.access;
94
	return found;
95
96
}

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

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

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

Alessio Netti's avatar
Alessio Netti committed
129
void sigHandler(int sig) {
130
	boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;
Alessio Netti's avatar
Alessio Netti committed
131
	if (sig == SIGINT) {
Alessio Netti's avatar
Alessio Netti committed
132
		LOG(fatal) << "Received SIGINT";
Alessio Netti's avatar
Alessio Netti committed
133
134
		retCode = 0;
	} else if (sig == SIGTERM) {
Alessio Netti's avatar
Alessio Netti committed
135
		LOG(fatal) << "Received SIGTERM";
Alessio Netti's avatar
Alessio Netti committed
136
137
138
139
140
		retCode = 0;
	} else if( sig == SIGUSR1 ) {
		LOG(fatal) << "Received SIGUSR1 via REST API";
		retCode = !_httpsServer ? EXIT_SUCCESS : _httpsServer->getReturnCode();
	}
141

142
143
	//Stop data analytics plugins and operators
	_operatorManager->stop();
144

145
146
	//Stop all sensors
	LOG(info) << "Stopping sensors...";
147
	_pluginManager->stopPlugin();
148

149
150
	//Stop io service by killing keepAliveWork
	keepAliveWork.reset();
151
152
153
154

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

157
158
void printSyntax() {
	/*
159
160
161
162
                       1         2         3         4         5         6         7         8
             012345678901234567890123456789012345678901234567890123456789012345678901234567890
*/
	cout << "Usage:" << endl;
163
	cout << "  dcdbpusher [-d] [-x] [-a] [-b<host>] [-m<string>] [-w<path>] [-v<level>] <config>" << endl;
164
165
166
167
	cout << "  dcdbpusher -h" << endl;
	cout << endl;

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

181
182
183
int main(int argc, char **argv) {
	cout << "dcdbpusher " << VERSION << endl
	     << endl;
184
	boost::asio::io_service io;
185
	boost::thread_group     threads;
186

187
	if (argc <= 1) {
188
		cout << "Please specify a path to the config-directory or a config-file" << endl
189
		     << endl;
190
		printSyntax();
191
192
193
		return 1;
	}

194
	//define allowed command-line options once
195
	const char opts[] = "b:p:m:v:w:dxah";
196

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

220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
	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);
243
					globalSettings.brokerPort = parseNetworkPort(optarg) == "" ? DEFAULT_BROKERPORT : stoi(parseNetworkPort(optarg));
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
					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;
			}
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
		
		//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!";
314
			}
315
			_queryEngine.setNavigator(navigator);
316
		}
317
318
319
320
		
		_queryEngine.setFilter(analyticsSettings.filter);
		_queryEngine.setJobFilter(analyticsSettings.jobFilter);
		_queryEngine.setJobMatch(analyticsSettings.jobMatch);
321
		_queryEngine.setJobIDFilter(analyticsSettings.jobIdFilter);
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
		_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();
					}
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
			_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");
384
		LOG(info) << "    Job ID Filter:      " << (analyticsSettings.jobIdFilter != "" ? analyticsSettings.jobIdFilter : "none");
385
386
387
388
389
390
391
392
393
394
395
396
397
		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  -----";
398
		for (auto &p : _operatorManager->getPlugins()) {
399
400
			LOG_VAR(vLogLevel) << "Operator Plugin \"" << p.id << "\"";
			p.configurator->printConfig(vLogLevel);
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
		
		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
Alessio Netti's avatar
Alessio Netti committed
472
		signal(SIGUSR1, sigHandler); // Handle user-requested termination
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
500
501
502
503
		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;
504
	}
505
506
507
	catch (const std::runtime_error& e) {
		LOG(fatal) <<  e.what();
		return EXIT_FAILURE;
508
	}
509
510
511
	catch (const exception& e) {
		LOG(fatal) << "Exception: " << e.what();
		abrt(EXIT_FAILURE, INTERR);
512
	}
513
	
Micha Mueller's avatar
Micha Mueller committed
514
	LOG(info) << "Exiting...Goodbye!";
Alessio Netti's avatar
Alessio Netti committed
515
	return retCode;
516
}