OpenSDN source code
controller/src/dns/main.cc
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
3  * Copyright Contributors to the OpenSDN project
4  */
5 
6 #include <csignal>
7 #include <fstream>
8 
9 #include <pthread.h>
10 #include <boost/program_options.hpp>
11 #include "nodeinfo_types.h"
12 #include "base/connection_info.h"
13 #include <base/logging.h>
14 #include <base/misc_utils.h>
15 #include <base/contrail_ports.h>
16 #include <base/task.h>
17 #include <io/process_signal.h>
18 #include <config_client_manager.h>
19 #include <db/db_graph.h>
21 #include <ifmap/ifmap_link_table.h>
23 #include <ifmap/ifmap_server.h>
24 #include <ifmap/ifmap_xmpp.h>
25 #include <io/event_manager.h>
26 #include <vnc_cfg_types.h>
27 #include <cmn/dns.h>
28 #include <bind/bind_util.h>
29 #include <mgr/dns_mgr.h>
30 #include <mgr/dns_oper.h>
31 #include <bind/named_config.h>
32 #include <cfg/dns_config.h>
33 #include <cfg/dns_config_parser.h>
34 #include <agent/agent_xmpp_init.h>
35 #include "cmn/dns_options.h"
36 #include <sandesh/common/vns_types.h>
37 #include <sandesh/common/vns_constants.h>
38 #include <uve/uve.h>
39 #include "xmpp/xmpp_sandesh.h"
41 
42 namespace opt = boost::program_options;
43 using namespace boost::asio::ip;
44 using namespace std;
45 using process::ConnectionInfo;
48 using process::ProcessState;
49 using process::ConnectionType;
51 using process::g_process_info_constants;
52 using process::Signal;
53 
54 uint64_t start_time;
58 
59 static void WaitForIdle(long wait_seconds = 1200, bool running_only = false);
60 static void WaitForIdle(long wait_seconds, bool running_only) {
61  static const long kTimeoutUsecs = 1000;
62  static long envWaitTime;
63 
64  if (!envWaitTime) {
65  if (getenv("WAIT_FOR_IDLE")) {
66  envWaitTime = atoi(getenv("WAIT_FOR_IDLE"));
67  } else {
68  envWaitTime = wait_seconds;
69  }
70  }
71 
72  if (envWaitTime > wait_seconds) wait_seconds = envWaitTime;
73 
75  for (long i = 0; i < ((wait_seconds * 1000000)/kTimeoutUsecs); i++) {
76  if (scheduler->IsEmpty(running_only)) {
77  return;
78  }
79  usleep(kTimeoutUsecs);
80  }
81 }
82 
83 static void PrintBulkSyncStats(DB *database) {
84  DNS_OPERATIONAL_LOG(
85  g_vns_constants.CategoryNames.find(Category::DNSAGENT)->second,
86  SandeshLevel::SYS_NOTICE, "EndOfRib point was reached, "
87  "IF-MAP objects have been created");
88  uint32_t ntypes = DnsConfigManager::config_types_size / sizeof(const char *);
89  for (uint32_t i=0; i<ntypes; i++) {
90  const char *type_name = DnsConfigManager::config_types[i];
91  IFMapTable *table = IFMapTable::FindTable(database, type_name);
92  std::stringstream msg_str;
93  msg_str << "The IF-MAP database table has been updated: "
94  << table->name()
95  << ", counting " << table->Size() << " elements";
96 
97  DNS_OPERATIONAL_LOG(
98  g_vns_constants.CategoryNames.find(Category::DNSAGENT)->second,
99  SandeshLevel::SYS_NOTICE, msg_str.str().c_str());
100  }
101 
102  {
103  std::stringstream msg_str;
104  msg_str << "VnniConfig has been updated after"
105  << " the bulk sync, the number of elements: "
106  << VnniConfig::vnni_config_.size();
107  DNS_OPERATIONAL_LOG(
108  g_vns_constants.CategoryNames.find(Category::DNSAGENT)->second,
109  SandeshLevel::SYS_NOTICE,
110  msg_str.str().c_str());
111  }
112 
113  {
114  std::stringstream msg_str;
115  msg_str << "IpamConfig has been updated after"
116  << " the bulk sync, the number of elements: "
117  << IpamConfig::ipam_config_.size();
118  DNS_OPERATIONAL_LOG(
119  g_vns_constants.CategoryNames.find(Category::DNSAGENT)->second,
120  SandeshLevel::SYS_NOTICE,
121  msg_str.str().c_str());
122  }
123 
124  {
125  std::stringstream msg_str;
126  msg_str << "VirtualDnsConfig has been updated after"
127  << " the bulk sync, the number of elements: "
129  DNS_OPERATIONAL_LOG(
130  g_vns_constants.CategoryNames.find(Category::DNSAGENT)->second,
131  SandeshLevel::SYS_NOTICE,
132  msg_str.str().c_str());
133  }
134 
135  {
136  std::stringstream msg_str;
137  msg_str << "VirtualDnsRecordConfig has been updated after"
138  << " the bulk sync, the number of elements: "
140  DNS_OPERATIONAL_LOG(
141  g_vns_constants.CategoryNames.find(Category::DNSAGENT)->second,
142  SandeshLevel::SYS_NOTICE,
143  msg_str.str().c_str());
144  }
145 
146  {
147  std::stringstream msg_str;
148  msg_str << "GlobalQosConfig has been updated after"
149  << " the bulk sync";
150  DNS_OPERATIONAL_LOG(
151  g_vns_constants.CategoryNames.find(Category::DNSAGENT)->second,
152  SandeshLevel::SYS_NOTICE,
153  msg_str.str().c_str());
154  }
155 }
156 
159  return false;
160 }
161 
164 
166  dns_info_log_timer->Start(60*1000, boost::bind(&DnsInfoLogTimer),NULL);
167  return true;
168 }
169 
171  const ConfigClientManager *config_client_manager,
172  const std::vector<ConnectionInfo> &cinfos,
173  ProcessState::type &state, std::string &message,
174  std::vector<ConnectionTypeName> expected_connections) {
175  GetProcessStateCb(cinfos, state, message, expected_connections);
176  if (state == ProcessState::NON_FUNCTIONAL)
177  return;
178  if (!config_client_manager->GetEndOfRibComputed()) {
179  state = ProcessState::NON_FUNCTIONAL;
180  message = "IFMap Server End-Of-RIB not computed";
181  }
182 }
183 
184 static string FileRead(const string &filename) {
185  ifstream file(filename.c_str());
186  string content((istreambuf_iterator<char>(file)),
187  istreambuf_iterator<char>());
188  return content;
189 }
190 
191 static void IFMap_Initialize(IFMapServer *server, ConfigJsonParser *json_parser) {
192  IFMapLinkTable_Init(server->database(), server->graph());
193  vnc_cfg_JsonParserInit(json_parser);
194  vnc_cfg_Server_ModuleInit(server->database(), server->graph());
195  server->Initialize();
196 }
197 
198 static bool OptionsParse(Options &options, int argc, char *argv[]) {
199  try {
200  options.Parse(*Dns::GetEventManager(), argc, argv);
201  return true;
202  } catch (boost::program_options::error &e) {
203  cout << "Error " << e.what() << endl;
204  } catch (...) {
205  cout << "Options Parser: Caught fatal unknown exception" << endl;
206  }
207 
208  return false;
209 }
210 
211 void ReConfigSignalHandler(const boost::system::error_code &error, int sig) {
212  if (error) {
213  LOG(ERROR, "SIGHUP handler ERROR: " << error);
214  return;
215  }
216  options.ParseReConfig();
217 }
218 
219 int main(int argc, char *argv[]) {
220  Logging logging;
221  // Initialize the task scheduler
222  int num_threads_to_tbb = TaskScheduler::GetDefaultThreadCount() +
224  TaskScheduler::Initialize(num_threads_to_tbb);
225 
226  // Create DB table and event manager
227  Dns::Init();
228 
229  // Process options from command-line and configuration file.
230  if (!OptionsParse(options, argc, argv)) {
231  exit(-1);
232  }
233 
234  srand(unsigned(time(NULL)));
235  std::vector<Signal::SignalHandler> sighup_handlers = boost::assign::list_of
236  (boost::bind(&ReConfigSignalHandler, _1, _2));
237  Signal::SignalCallbackMap smap = boost::assign::map_list_of
238  (SIGHUP, sighup_handlers);
239  Signal signal(Dns::GetEventManager(), smap);
240 
241  Dns::SetProgramName(argv[0]);
242  Module::type module = Module::DNS;
243  string module_name = g_vns_constants.ModuleNames.find(module)->second;
244 
245  std::string log_property_file = options.log_property_file();
246  if (log_property_file.size()) {
247  logging.Init(log_property_file);
248  }
249  else {
250  logging.Init(options.log_file(), options.log_file_size(),
251  options.log_files_count(), options.use_syslog(),
252  options.syslog_facility(), module_name,
254  Sandesh::StringToLevel(options.log_level())));
255  }
256 
257  string build_info_str;
258  Dns::GetVersion(build_info_str);
259  MiscUtils::LogVersionInfo(build_info_str, Category::DNSAGENT);
260 
261  if (options.collectors_configured()) {
262  Dns::SetCollector(options.collector_server_list()[0]);
263  }
264  Dns::SetHttpPort(options.http_server_port());
265  Dns::SetDnsPort(options.dns_server_port());
266 
267  string hostname = options.hostname();
268  Dns::SetHostName(hostname);
269 
270  ConnectionStateManager::GetInstance();
271  NodeType::type node_type =
272  g_vns_constants.Module2NodeType.find(module)->second;
273  bool success;
274  if (options.collectors_configured()) {
275  success = Sandesh::InitGenerator(
276  module_name,
277  options.hostname(),
278  g_vns_constants.NodeTypeNames.find(node_type)->second,
279  g_vns_constants.INSTANCE_ID_DEFAULT,
281  options.http_server_port(),
282  options.randomized_collector_server_list(),
283  NULL,
285  options.sandesh_config());
286  } else {
287  success = Sandesh::InitGenerator(
288  g_vns_constants.ModuleNames.find(module)->second,
289  options.hostname(),
290  g_vns_constants.NodeTypeNames.find(node_type)->second,
291  g_vns_constants.INSTANCE_ID_DEFAULT,
293  options.http_server_port(),
294  NULL,
296  options.sandesh_config());
297  }
298  if (!success) {
299  LOG(ERROR, "SANDESH: Initialization FAILED ... exiting");
300  Sandesh::Uninit();
301  exit(1);
302  }
303  Sandesh::SetLoggingParams(options.log_local(), options.log_category(),
304  options.log_level());
305 
306  // XXX Disable logging -- for test purposes only
307  if (options.log_disable()) {
308  SetLoggingDisabled(true);
309  }
310 
311  // DNS::SetTestMode(options.test_mode());
312 
313  DB config_db(TaskScheduler::GetInstance()->GetTaskId("db::IFMapTable"));
314  DBGraph config_graph;
315  IFMapServer ifmap_server(&config_db, &config_graph,
316  Dns::GetEventManager()->io_service());
317 
319  ConfigJsonParser>();
320  boost::scoped_ptr<ConfigClientManager> config_client_manager_ptr(
322  ConfigStaticObjectFactory::Create<ConfigJsonParserBase>(),
323  options.hostname(),
324  module_name,
325  options.configdb_options()));
326  ConfigClientManager *config_client_manager = config_client_manager_ptr.get();
327  ConfigJsonParser *json_parser = static_cast<ConfigJsonParser *>(
328  config_client_manager->config_json_parser());
329  json_parser->ifmap_server_set(&ifmap_server);
330  IFMap_Initialize(&ifmap_server, json_parser);
331 
332 
333  DnsManager dns_manager;
334  Dns::SetDnsManager(&dns_manager);
335  dns_manager.Initialize(&config_db, &config_graph,
336  options.named_config_dir(),
337  options.named_config_file(),
338  options.named_log_file(),
339  options.rndc_config_file(),
340  options.rndc_secret(),
341  options.named_max_cache_size(),
342  options.named_max_retransmissions(),
343  options.named_retransmission_interval());
344  DnsConfigParser parser(&config_db);
345  parser.Parse(FileRead(options.config_file()));
346 
347  Dns::SetSelfIp(options.host_ip());
348  if (!DnsAgentXmppManager::Init(options.xmpp_auth_enabled(),
349  options.xmpp_server_cert(),
350  options.xmpp_server_key(),
351  options.xmpp_ca_cert())) {
352  LOG(ERROR, "Address already in use " << ContrailPorts::DnsXmpp());
353  exit(1);
354  }
355 
356  XmppSandeshContext xmpp_sandesh_context;
357  xmpp_sandesh_context.xmpp_server = Dns::GetXmppServer();
358  Sandesh::set_module_context("XMPP", &xmpp_sandesh_context);
359  IFMapSandeshContext ifmap_sandesh_context(&ifmap_server);
360  Sandesh::set_module_context("IFMap", &ifmap_sandesh_context);
361 
364  new TaskTrigger(boost::bind(&DnsInfoLogger),
365  TaskScheduler::GetInstance()->GetTaskId("dns::Config"), 0);
366 
369  "Dns Info log timer");
370  dns_info_log_timer->Start(60*1000, boost::bind(&DnsInfoLogTimer), NULL);
371  Dns::SetSelfIp(options.host_ip());
372  ifmap_server.set_config_manager(config_client_manager);
373 
374  //
375  // Determine if the number of connections is as expected.
376  // 1. Cassandra Server
377  // 2. AMQP Server
378  //
379  std::vector<ConnectionTypeName> expected_connections;
380  expected_connections = boost::assign::list_of
381  (ConnectionTypeName(g_process_info_constants.ConnectionTypeNames.find(
382  ConnectionType::DATABASE)->second, "Cassandra"))
383  (ConnectionTypeName(g_process_info_constants.ConnectionTypeNames.find(
384  ConnectionType::DATABASE)->second, "RabbitMQ"))
385  (ConnectionTypeName(g_process_info_constants.ConnectionTypeNames.find(
386  ConnectionType::COLLECTOR)->second, ""))
387  .convert_to_container\
388  <vector<ConnectionTypeName> >();
389 
390  if (!options.collectors_configured()) {
391  LOG(INFO, "DNS: Collectors are not configured!");
392  expected_connections.pop_back();
393  }
394 
395  ConnectionStateManager::GetInstance()->Init(
396  *(Dns::GetEventManager()->io_service()), options.hostname(),
397  module_name, g_vns_constants.INSTANCE_ID_DEFAULT,
398  boost::bind(&DnsServerGetProcessStateCb, config_client_manager, _1, _2, _3,
399  expected_connections), "ObjectDns");
400 
401  dns_manager.set_config_manager(config_client_manager);
402  options.set_config_client_manager(config_client_manager);
403  DNS_OPERATIONAL_LOG(
404  g_vns_constants.CategoryNames.find(Category::DNSAGENT)->second,
405  SandeshLevel::SYS_NOTICE, "Bulk sync has been started");
406  config_client_manager->Initialize();
407  config_client_manager->config_amqp_client()->set_terminate(true);
408  WaitForIdle(); // 20 mins
409  PrintBulkSyncStats(&config_db);
410  config_client_manager->config_amqp_client()->set_terminate(false);
411  config_client_manager->config_amqp_client()->StartRabbitMQReader();
412  dns_manager.StartEndofConfigTimer();
414  signal.Terminate();
415  return 0;
416 }
void set_terminate(bool terminate)
ConfigJsonParserBase * config_json_parser()
ConfigAmqpClient * config_amqp_client() const
void ifmap_server_set(IFMapServer *ifmap_server)
static const uint16_t DnsXmpp()
const std::string & name() const
Definition: db_table.h:111
virtual size_t Size() const
Definition: db_table.cc:534
Definition: db.h:25
static bool Init(bool xmpp_auth_enabled, const std::string &xmpp_server_cert, const std::string &xmpp_server_key, const std::string &xmpp_ca_cert)
static const char * config_types[]
Definition: dns_config.h:84
static uint32_t config_types_size
Definition: dns_config.h:85
void StartEndofConfigTimer()
Definition: dns_mgr.cc:851
void Initialize(DB *config_db, DBGraph *config_graph, const std::string &named_config_dir, const std::string &named_config_file, const std::string &named_log_file, const std::string &rndc_config_file, const std::string &rndc_secret, const std::string &named_max_cache_size, const uint16_t named_max_retransmissions, const uint16_t named_retransmission_interval)
Definition: dns_mgr.cc:67
void set_config_manager(ConfigClientManager *config_manager)
Definition: dns_mgr.h:91
static void SendDnsUve(uint64_t start_time)
Definition: uve.cc:15
static void SetCollector(std::string name)
Definition: dns.h:61
static void Init()
Definition: dns.h:70
static void SetSelfIp(std::string ip)
Definition: dns.h:67
static EventManager * GetEventManager()
Definition: dns.h:34
static void SetDnsManager(DnsManager *mgr)
Definition: dns.h:38
static void SetProgramName(const char *name)
Definition: dns.h:59
static void SetDnsPort(uint32_t port)
Definition: dns.h:65
static void SetHostName(const std::string name)
Definition: dns.h:57
static bool GetVersion(std::string &build_info_str)
Definition: dns.cc:33
static void SetHttpPort(uint32_t port)
Definition: dns.h:63
static XmppServer * GetXmppServer()
Definition: dns.h:43
void Initialize()
DB * database()
Definition: ifmap_server.h:83
DBGraph * graph()
Definition: ifmap_server.h:84
static IFMapTable * FindTable(DB *db, const std::string &element_type)
Definition: ifmap_table.cc:40
A class providing basic control over logging capabilities in OpenSDN control plane.
Definition: logging.h:44
void Init()
Performs basic initialization of the logging system ( log4cplus).
Definition: logging.cc:32
static void LogVersionInfo(const std::string str, Category::type categ)
Definition: misc_utils.cc:37
static void set_module_context(const std::string &module_name, SandeshContext *context)
Definition: sandesh.cc:959
static bool InitGenerator(const std::string &module, const std::string &source, const std::string &node_type, const std::string &instance_id, EventManager *evm, unsigned short http_port, const std::vector< std::string > &collectors, SandeshContext *client_context=NULL, DerivedStats ds=DerivedStats(), const SandeshConfig &config=SandeshConfig())
Definition: sandesh.cc:273
std::map< std::string, std::map< std::string, std::string > > DerivedStats
Definition: cpp/sandesh.h:151
static void Uninit()
Definition: sandesh.cc:343
static void SetLoggingParams(bool enable_local_log, std::string category, std::string level, bool enable_trace_print=false, bool enable_flow_log=false, bool enable_session_syslog=false)
Definition: sandesh.cc:371
static SandeshLevel::type StringToLevel(std::string level)
Definition: sandesh.cc:863
The TaskScheduler keeps track of what tasks are currently schedulable. When a task is enqueued it is ...
Definition: task.h:307
static int GetDefaultThreadCount()
Definition: task.cc:452
static void Initialize(uint32_t thread_count=0, EventManager *evm=NULL)
Definition: task.cc:505
static TaskScheduler * GetInstance()
Definition: task.cc:574
bool IsEmpty(bool running_only=false)
Returns true if there are no tasks running and/or enqueued If running_only is true,...
Definition: task.cc:851
static Timer * CreateTimer(boost::asio::io_context &service, const std::string &name, int task_id=Timer::GetTimerTaskId(), int task_instance=Timer::GetTimerInstanceId(), bool delete_on_completion=false)
Definition: timer.cc:201
Definition: timer.h:58
bool Cancel()
Definition: timer.cc:150
bool Start(int time, Handler handler, ErrorHandler error_handler=NULL)
Definition: timer.cc:108
static void WaitForIdle(long wait_seconds=1200, bool running_only=false)
static bool OptionsParse(Options &options, int argc, char *argv[])
static Options options
static void IFMap_Initialize(IFMapServer *server, ConfigJsonParser *json_parser)
uint64_t start_time
bool DnsInfoLogger()
bool DnsInfoLogTimer()
static void PrintBulkSyncStats(DB *database)
Timer * dns_info_log_timer
TaskTrigger * dns_info_trigger
static void DnsServerGetProcessStateCb(const ConfigClientManager *config_client_manager, const std::vector< ConnectionInfo > &cinfos, ProcessState::type &state, std::string &message, std::vector< ConnectionTypeName > expected_connections)
static string FileRead(const string &filename)
void ReConfigSignalHandler(const boost::system::error_code &error, int sig)
uint8_t type
Definition: load_balance.h:2
void SetLoggingDisabled(bool flag)
Definition: logging.cc:60
#define LOG(_Level, _Msg)
Definition: logging.h:35
void GetProcessStateCb(const vector< ConnectionInfo > &cinfos, ProcessState::type &state, string &message, const vector< ConnectionTypeName > &expected_connections)
std::pair< std::string, std::string > ConnectionTypeName
log4cplus::LogLevel SandeshLevelTolog4Level(SandeshLevel::type slevel)
Definition: sandesh.cc:397
static DataMap ipam_config_
Definition: dns_oper.h:109
static void LinkImpl()
Definition: factory.h:69
static DataMap virt_dns_config_
Definition: dns_oper.h:147
static DataMap virt_dns_rec_config_
Definition: dns_oper.h:202
static DataMap vnni_config_
Definition: dns_oper.h:80
XmppServer * xmpp_server
Definition: xmpp_sandesh.h:17
static uint64_t UTCTimestampUsec()
Definition: time_util.h:14