-
Notifications
You must be signed in to change notification settings - Fork 390
/
main.cc
452 lines (394 loc) · 15.3 KB
/
main.cc
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
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
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
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
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
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
389
390
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
/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <fstream>
#include <boost/asio/ip/host_name.hpp>
#include <boost/program_options.hpp>
#include <boost/tokenizer.hpp>
#include <malloc.h>
#include "analytics/options.h"
#include "analytics/viz_constants.h"
#include "base/cpuinfo.h"
#include "boost/python.hpp"
#include "base/logging.h"
#include "base/contrail_ports.h"
#include "base/task.h"
#include "base/task_trigger.h"
#include "base/timer.h"
#include "base/connection_info.h"
#include "base/misc_utils.h"
#include "io/event_manager.h"
#include <sandesh/sandesh_types.h>
#include <sandesh/sandesh.h>
#include <sandesh/common/vns_types.h>
#include <sandesh/common/vns_constants.h>
#include "gendb_if.h"
#include "viz_collector.h"
#include "viz_sandesh.h"
#include "ruleeng.h"
#include "viz_types.h"
#include "analytics_types.h"
#include "generator.h"
#include <base/misc_utils.h>
#include <analytics/buildinfo.h>
#include <discovery/client/discovery_client.h>
#include "boost/python.hpp"
using namespace std;
using namespace boost::asio::ip;
namespace opt = boost::program_options;
using process::ConnectionStateManager;
using process::GetProcessStateCb;
using process::ConnectionType;
using process::ConnectionTypeName;
using process::g_process_info_constants;
static TaskTrigger *collector_info_trigger;
static Timer *collector_info_log_timer;
static EventManager * a_evm = NULL;
bool CollectorInfoLogTimer() {
collector_info_trigger->Set();
return false;
}
bool CollectorVersion(string &version) {
return MiscUtils::GetBuildInfo(MiscUtils::Analytics, BuildInfo, version);
}
bool CollectorCPULogger(const string & hostname) {
CpuLoadInfo cpu_load_info;
CpuLoadData::FillCpuInfo(cpu_load_info, false);
ModuleCpuState state;
state.set_name(hostname);
ModuleCpuInfo cinfo;
cinfo.set_module_id(Sandesh::module());
cinfo.set_instance_id(Sandesh::instance_id());
cinfo.set_cpu_info(cpu_load_info);
vector<ModuleCpuInfo> cciv;
cciv.push_back(cinfo);
// At some point, the following attributes will be deprecated
// in favor of AnalyticsCpuState
state.set_module_cpu_info(cciv);
ModuleCpuStateTrace::Send(state);
SendCpuInfoStat<AnalyticsCpuStateTrace, AnalyticsCpuState>(hostname,
cpu_load_info);
return true;
}
bool CollectorSummaryLogger(Collector *collector, const string & hostname,
OpServerProxy * osp) {
CollectorState state;
static bool first = true, build_info_set = false;
state.set_name(hostname);
if (first) {
vector<string> ip_list;
ip_list.push_back(Collector::GetSelfIp());
state.set_self_ip_list(ip_list);
first = false;
}
if (!build_info_set) {
string build_info_str;
build_info_set = CollectorVersion(build_info_str);
state.set_build_info(build_info_str);
}
std::vector<GeneratorSummaryInfo> infos;
collector->GetGeneratorSummaryInfo(&infos);
state.set_generator_infos(infos);
// Get socket stats
SocketIOStats rx_stats;
collector->GetRxSocketStats(rx_stats);
state.set_rx_socket_stats(rx_stats);
SocketIOStats tx_stats;
collector->GetTxSocketStats(tx_stats);
state.set_tx_socket_stats(tx_stats);
CollectorInfo::Send(state);
return true;
}
bool CollectorInfoLogger(VizSandeshContext &ctx) {
VizCollector *analytics = ctx.Analytics();
CollectorCPULogger(analytics->name());
CollectorSummaryLogger(analytics->GetCollector(), analytics->name(),
analytics->GetOsp());
analytics->SendDbStatistics();
analytics->SendProtobufCollectorStatistics();
vector<ModuleServerState> sinfos;
analytics->GetCollector()->GetGeneratorUVEInfo(sinfos);
for (uint i = 0; i < sinfos.size(); i++) {
SandeshModuleServerTrace::Send(sinfos[i]);
}
analytics->SendGeneratorStatistics();
analytics->TestDatabaseConnection();
collector_info_log_timer->Cancel();
collector_info_log_timer->Start(60*1000, boost::bind(&CollectorInfoLogTimer),
NULL);
return true;
}
// Trigger graceful shutdown of collector process.
//
// IO (evm) is shutdown first. Afterwards, main() resumes, shutting down rest of the
// objects, and eventually exit()s.
void CollectorShutdown() {
static bool shutdown_;
if (shutdown_) return;
shutdown_ = true;
// Shutdown event manager first to stop all IO activities.
a_evm->Shutdown();
}
static void terminate(int param) {
// Shutdown can result in a malloc-detected error
// Taking a stack trace during this error can result in
// the process not terminating correctly
// using mallopt in this way ensures that we get a core,
// but we don't print a stack trace
mallopt(M_CHECK_ACTION, 2);
CollectorShutdown();
}
static void ShutdownDiscoveryClient(DiscoveryServiceClient *client) {
if (client) {
client->Shutdown();
delete client;
}
}
// Shutdown various objects used in the collector.
static void ShutdownServers(VizCollector *viz_collector,
DiscoveryServiceClient *client) {
// Shutdown discovery client first
ShutdownDiscoveryClient(client);
Sandesh::Uninit();
viz_collector->Shutdown();
if (collector_info_log_timer) {
TimerManager::DeleteTimer(collector_info_log_timer);
delete collector_info_trigger;
collector_info_log_timer = NULL;
}
ConnectionStateManager<NodeStatusUVE, NodeStatus>::
GetInstance()->Shutdown();
VizCollector::WaitForIdle();
}
static bool OptionsParse(Options &options, int argc, char *argv[]) {
try {
options.Parse(*a_evm, argc, argv);
return true;
} catch (boost::program_options::error &e) {
cout << "Error " << e.what() << endl;
} catch (...) {
cout << "Options Parser: Caught fatal unknown exception" << endl;
}
return false;
}
// This is to force vizd to wait for a gdbattach
// before proceeding.
// It will make it easier to debug vizd during systest
volatile int gdbhelper = 1;
int main(int argc, char *argv[])
{
a_evm = new EventManager();
Options options;
if (!OptionsParse(options, argc, argv)) {
exit(-1);
}
while (gdbhelper==0) {
usleep(1000);
}
Collector::SetProgramName(argv[0]);
Module::type module = Module::COLLECTOR;
std::string module_id(g_vns_constants.ModuleNames.find(module)->second);
NodeType::type node_type =
g_vns_constants.Module2NodeType.find(module)->second;
std::string instance_id(g_vns_constants.INSTANCE_ID_DEFAULT);
std::string log_property_file = options.log_property_file();
if (log_property_file.size()) {
LoggingInit(log_property_file);
} else {
LoggingInit(options.log_file(), options.log_file_size(),
options.log_files_count(), options.use_syslog(),
options.syslog_facility(), module_id,
SandeshLevelTolog4Level(
Sandesh::StringToLevel(options.log_level())));
}
vector<string> cassandra_servers(options.cassandra_server_list());
vector<string> cassandra_ips;
vector<int> cassandra_ports;
for (vector<string>::const_iterator it = cassandra_servers.begin();
it != cassandra_servers.end(); it++) {
string cassandra_server(*it);
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> sep(":");
tokenizer tokens(cassandra_server, sep);
tokenizer::iterator tit = tokens.begin();
string cassandra_ip(*tit);
cassandra_ips.push_back(cassandra_ip);
++tit;
string port(*tit);
int cassandra_port;
stringToInteger(port, cassandra_port);
cassandra_ports.push_back(cassandra_port);
}
LOG(INFO, "COLLECTOR LISTEN PORT: " << options.collector_port());
LOG(INFO, "COLLECTOR REDIS UVE PORT: " << options.redis_port());
ostringstream css;
copy(cassandra_servers.begin(), cassandra_servers.end(),
ostream_iterator<string>(css, " "));
LOG(INFO, "COLLECTOR CASSANDRA SERVERS: " << css.str());
LOG(INFO, "COLLECTOR ZOOKEEPER SERVERS: " <<
options.zookeeper_server_list());
LOG(INFO, "COLLECTOR SYSLOG LISTEN PORT: " << options.syslog_port());
LOG(INFO, "COLLECTOR SFLOW LISTEN PORT: " << options.sflow_port());
LOG(INFO, "COLLECTOR IPFIX LISTEN PORT: " << options.ipfix_port());
uint16_t protobuf_port(0);
bool protobuf_server_enabled =
options.collector_protobuf_port(&protobuf_port);
if (protobuf_server_enabled) {
LOG(INFO, "COLLECTOR PROTOBUF LISTEN PORT: " << protobuf_port);
}
string kstr("");
vector<string> kbl = options.kafka_broker_list();
for (vector<string>::const_iterator st = kbl.begin();
st != kbl.end(); st++) {
if (st != kbl.begin()) {
kstr += string(",");
}
kstr += *st;
}
LOG(INFO, "KAFKA BROKERS: " << kstr);
std::string hostname;
boost::system::error_code error;
if (options.dup()) {
hostname = boost::asio::ip::host_name(error) + "dup";
} else {
hostname = boost::asio::ip::host_name(error);
}
// Determine if the number of connections is expected:
// 1. Collector client
// 2. Redis From
// 3. Redis To
// 4. Discovery Collector Publish
// 5. Database global
// 6. Kafka Pub
// 7. Database protobuf if enabled
std::vector<ConnectionTypeName> expected_connections = boost::assign::list_of
(ConnectionTypeName(g_process_info_constants.ConnectionTypeNames.find(
ConnectionType::COLLECTOR)->second, ""))
(ConnectionTypeName(g_process_info_constants.ConnectionTypeNames.find(
ConnectionType::REDIS_UVE)->second, "To"))
(ConnectionTypeName(g_process_info_constants.ConnectionTypeNames.find(
ConnectionType::REDIS_UVE)->second, "From"))
(ConnectionTypeName(g_process_info_constants.ConnectionTypeNames.find(
ConnectionType::DISCOVERY)->second,
g_vns_constants.COLLECTOR_DISCOVERY_SERVICE_NAME))
(ConnectionTypeName(g_process_info_constants.ConnectionTypeNames.find(
ConnectionType::DATABASE)->second,
hostname+":Global"))
(ConnectionTypeName(g_process_info_constants.ConnectionTypeNames.find(
ConnectionType::KAFKA_PUB)->second, kstr));
ConnectionStateManager<NodeStatusUVE, NodeStatus>::
GetInstance()->Init(*a_evm->io_service(),
hostname, module_id, instance_id,
boost::bind(&GetProcessStateCb, _1, _2, _3,
expected_connections));
LOG(INFO, "COLLECTOR analytics_data_ttl: " << options.analytics_data_ttl());
LOG(INFO, "COLLECTOR analytics_flow_ttl: " << options.analytics_flow_ttl());
LOG(INFO, "COLLECTOR analytics_statistics_ttl: " <<
options.analytics_statistics_ttl());
LOG(INFO, "COLLECTOR analytics_config_audit_ttl: " <<
options.analytics_config_audit_ttl());
TtlMap ttl_map;
ttl_map.insert(std::make_pair(TtlType::FLOWDATA_TTL,
options.analytics_flow_ttl()));
ttl_map.insert(std::make_pair(TtlType::STATSDATA_TTL,
options.analytics_statistics_ttl()));
ttl_map.insert(std::make_pair(TtlType::CONFIGAUDIT_TTL,
options.analytics_config_audit_ttl()));
ttl_map.insert(std::make_pair(TtlType::GLOBAL_TTL,
options.analytics_data_ttl()));
//Get Platform info
//cql not supported in precise, centos 6.4 6.5
bool use_cql = MiscUtils::IsCqlSupported();
std::string zookeeper_server_list(options.zookeeper_server_list());
bool use_zookeeper = !zookeeper_server_list.empty();
VizCollector analytics(a_evm,
options.collector_port(),
protobuf_server_enabled,
protobuf_port,
cassandra_ips,
cassandra_ports,
string("127.0.0.1"),
options.redis_port(),
options.redis_password(),
kstr,
options.syslog_port(),
options.sflow_port(),
options.ipfix_port(),
options.partitions(),
options.dup(),
options.kafka_prefix(),
ttl_map, options.cassandra_user(),
options.cassandra_password(),
options.cassandra_compaction_strategy(),
options.cassandra_flow_tables_compaction_strategy(),
use_cql,
zookeeper_server_list,
use_zookeeper, options.disable_all_db_writes(),
options.disable_db_statistics_writes(),
options.disable_db_messages_writes(),
!options.enable_db_messages_keyword_writes());
#if 0
// initialize python/c++ API
Py_InitializeEx(0);
// insert the patch where scripts are placed
// temporary it is env variable RULEENGPATH
char *rpath = getenv("RULEENGPATH");
if (rpath != NULL) {
PyObject* sysPath = PySys_GetObject((char*)"path");
PyList_Insert(sysPath, 0, PyString_FromString(rpath));
}
#endif
analytics.Init();
unsigned short coll_port = analytics.GetCollector()->GetPort();
VizSandeshContext vsc(&analytics);
Sandesh::set_send_rate_limit(options.sandesh_send_rate_limit());
bool success(Sandesh::InitCollector(
module_id,
analytics.name(),
g_vns_constants.NodeTypeNames.find(node_type)->second,
instance_id,
a_evm, "127.0.0.1", coll_port,
options.http_server_port(), &vsc));
if (!success) {
LOG(ERROR, "SANDESH: Initialization FAILED ... exiting");
ShutdownServers(&analytics, NULL);
delete a_evm;
exit(1);
}
Sandesh::DisableFlowCollection(options.disable_flow_collection());
Sandesh::SetLoggingParams(options.log_local(), options.log_category(),
options.log_level());
// XXX Disable logging -- for test purposes only
if (options.log_disable()) {
SetLoggingDisabled(true);
}
// Get local ip address
Collector::SetSelfIp(options.host_ip());
//Publish services to Discovery Service Servee
DiscoveryServiceClient *ds_client = NULL;
tcp::endpoint dss_ep;
if (DiscoveryServiceClient::ParseDiscoveryServerConfig(
options.discovery_server(), options.discovery_port(), &dss_ep)) {
string client_name =
g_vns_constants.ModuleNames.find(Module::COLLECTOR)->second;
ds_client = new DiscoveryServiceClient(a_evm, dss_ep, client_name);
ds_client->Init();
} else {
LOG (ERROR, "Invalid Discovery Server hostname or ip " <<
options.discovery_server());
}
Collector::SetDiscoveryServiceClient(ds_client);
CpuLoadData::Init();
collector_info_trigger =
new TaskTrigger(boost::bind(&CollectorInfoLogger, vsc),
TaskScheduler::GetInstance()->GetTaskId("vizd::Stats"), 0);
collector_info_log_timer = TimerManager::CreateTimer(*a_evm->io_service(),
"Collector Info log timer",
TaskScheduler::GetInstance()->GetTaskId("vizd::Stats"), 0);
collector_info_log_timer->Start(5*1000, boost::bind(&CollectorInfoLogTimer), NULL);
signal(SIGTERM, terminate);
a_evm->Run();
ShutdownServers(&analytics, ds_client);
delete a_evm;
return 0;
}