OpenSDN source code
config_amqp_client.cc
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2017 Juniper Networks, Inc. All rights reserved.
3  * Copyright Contributors to the OpenSDN project
4  */
5 
6 #include "config_amqp_client.h"
7 
8 #include <boost/algorithm/string/find.hpp>
9 #include <boost/lexical_cast.hpp>
10 #include <stdio.h>
11 #include <string>
12 
13 #include <SimpleAmqpClient/SimpleAmqpClient.h>
14 #include "rapidjson/document.h"
15 
16 #include "base/connection_info.h"
17 #include "base/task.h"
18 #include "base/address_util.h"
19 #include "base/string_util.h"
20 #include "config_factory.h"
22 #include "config_client_log.h"
23 #include "config_client_log_types.h"
24 #include "config_client_manager.h"
25 #include "config_db_client.h"
26 #include "config_client_show_types.h"
27 
28 using namespace boost;
29 using namespace std;
30 using namespace contrail_rapidjson;
31 
33 
35 public:
37  Task(amqpclient->reader_task_id()), amqpclient_(amqpclient) {
38  channel_.reset(ConfigStaticObjectFactory::Create<ConfigAmqpChannel>());
39 
40  // Connect to rabbit-mq asap so that notification messages over
41  // rabbit mq are never missed (during bulk db sync which happens
42  // soon afterwards.
43  ConnectToRabbitMQ();
44  }
45 
46  virtual bool Run();
47  string Description() const { return "ConfigAmqpClient::RabbitMQReader"; }
48 
49 private:
51  boost::scoped_ptr<ConfigAmqpChannel> channel_;
52  string consumer_tag_;
53  void ConnectToRabbitMQ(bool queue_delete = true);
54  bool AckRabbitMessages(AmqpClient::Envelope::ptr_t &envelop);
55  bool ReceiveRabbitMessages(AmqpClient::Envelope::ptr_t &envelop);
56 };
57 
59  string module_name, const ConfigClientOptions &options) :
60  mgr_(mgr), hostname_(hostname), module_name_(module_name),
61  current_server_index_(0), terminate_(false),
62  rabbitmq_user_(options.rabbitmq_user),
63  rabbitmq_password_(options.rabbitmq_password),
64  rabbitmq_vhost_(options.rabbitmq_vhost),
65  rabbitmq_use_ssl_(options.rabbitmq_use_ssl),
66  rabbitmq_ssl_version_(options.rabbitmq_ssl_version),
67  rabbitmq_ssl_keyfile_(options.rabbitmq_ssl_keyfile),
68  rabbitmq_ssl_certfile_(options.rabbitmq_ssl_certfile),
69  rabbitmq_ssl_ca_certs_(options.rabbitmq_ssl_ca_certs) {
70 
71  connection_status_ = false;
73 
75  reader_task_id_ = scheduler->GetTaskId("amqp::RabbitMQReader");
76 
77  if (options.rabbitmq_server_list.empty())
78  return;
79 
80  for (vector<string>::const_iterator iter =
81  options.rabbitmq_server_list.begin();
82  iter != options.rabbitmq_server_list.end(); iter++) {
83  string server_info(*iter);
84  typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
85  boost::char_separator<char> sep(":");
86  tokenizer tokens(server_info, sep);
87  tokenizer::iterator tit = tokens.begin();
88  string ip(*tit);
89  rabbitmq_ips_.push_back(ip);
90  ++tit;
91  string port_str(*tit);
92  rabbitmq_ports_.push_back(port_str);
93  Endpoint curr_ep;
94  int port = 0;
95  stringToInteger(port_str, port);
96  boost::system::error_code ec;
97  curr_ep.address(AddressFromString(ip, &ec));
98  curr_ep.port(port);
99  endpoints_.push_back(curr_ep);
100  }
101 }
102 
104  if (disable_) {
106  ConfigClientMgrDebug,
107  "RabbitMQ SM: StartRabbitMQReader: RabbitMQ disabled");
108  return;
109  }
110 
111  // If reinit is triggerred, Don't start the rabbitmq reader
112  if (config_manager()->is_reinit_triggered()) {
114  ConfigClientMgrDebug,
115  "RabbitMQ SM: StartRabbitMQReader: re init triggered,"
116  " dont start RabbitMQ");
117  return;
118  }
120  Task *task = new RabbitMQReader(this);
121  scheduler->Enqueue(task);
122 }
123 
124 void ConfigAmqpClient::EnqueueUUIDRequest(string oper, string obj_type,
125  string uuid_str) {
126  if (mgr_->config_json_parser()->IsReadObjectType(obj_type)) {
127  mgr_->EnqueueUUIDRequest(oper, obj_type, uuid_str);
128  }
129 }
130 
131 string ConfigAmqpClient::FormAmqpUri(bool hide_auth_info) const {
132  const string user = hide_auth_info ? "********" : rabbitmq_user();
133  const string password = hide_auth_info ? "********" : rabbitmq_password();
134  string uri = string("amqp://" + user + ":" +
135  password + "@" + rabbitmq_ip() + ":" + rabbitmq_port());
136  if (!rabbitmq_vhost().empty()) {
137  if (rabbitmq_vhost().compare("/") != 0) {
138  uri += "/" + rabbitmq_vhost();
139  }
140  }
141  return uri;
142 }
143 
145  if (connected) {
146  // Update connection info
148  process::ConnectionType::DATABASE, "RabbitMQ",
149  process::ConnectionStatus::UP,
150  endpoints(), "RabbitMQ connection established");
151  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
152  "RabbitMQ SM: RabbitMQ connection established");
153  } else {
155  process::ConnectionType::DATABASE, "RabbitMQ",
156  process::ConnectionStatus::DOWN,
157  endpoints(), "RabbitMQ connection down");
158  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
159  "RabbitMQ SM: RabbitMQ connection down");
160  }
161 }
162 
165  amqpclient_->set_connected(false);
166  string message = "RabbitMQ SM: Connect to Rabbit MQ with queue_delete ";
167  message += queue_delete ? "TRUE" : "FALSE";
168  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug, message);
169  size_t count = 0;
170  while (true) {
171  // If we are signalled to stop, break now.
173  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
174  "RabbitMQ SM: Skipped connect due to reinit");
175  return;
176  }
177  string uri = amqpclient_->FormAmqpUri(false);
178  try {
179  if (amqpclient_->rabbitmq_use_ssl()) {
180  int port = boost::lexical_cast<int>(
182 
183  channel_->CreateSecure(
188  port,
192  } else {
193  channel_->CreateFromUri(uri);
194  }
195  // passive = false, durable = false, auto_delete = false
196  channel_->DeclareExchange("vnc_config.object-update",
197  AmqpClient::Channel::EXCHANGE_TYPE_FANOUT, false, false, false);
198  string queue_name =
200 
201  if (queue_delete) {
202  channel_->DeleteQueue(queue_name, false, false);
203  }
204 
205  // passive = false, durable = false,
206  // exclusive = false, auto_delete = false
207  string queue = channel_->DeclareQueue(queue_name, false, false,
208  false, false);
209  channel_->BindQueue(queue, "vnc_config.object-update");
210  // no_local = true, no_ack = false,
211  // exclusive = false, message_prefetch_count = 0
212  consumer_tag_ = channel_->BasicConsume(queue, queue_name,
213  true, false, false, 0);
214  } catch (std::exception &e) {
215  static string what = e.what();
216  string message =
217  "RabbitMQ SM: Caught exception while connecting to RabbitMQ: "
218  + amqpclient_->rabbitmq_ip() + ":"
219  + amqpclient_->rabbitmq_port() + " : " + what;
220  cout << message << endl;
221  CONFIG_CLIENT_WARN(ConfigClientMgrWarning, message);
222  if (++count == amqpclient_->rabbitmq_server_list_len()) {
223  count = 0;
224  // Tried connecting to all given servers.. Now wait to reconnect
225  sleep(5);
226  }
228  continue;
229  } catch (...) {
230  string message =
231  "RabbitMQ SM: Caught fatal exception while "
232  "connecting to RabbitMQ: "
233  + amqpclient_->rabbitmq_ip() + ":"
235  cout << message << endl;
236  CONFIG_CLIENT_WARN(ConfigClientMgrWarning, message);
237  assert(0);
238  }
239 
241  amqpclient_->set_connected(true);
242  break;
243  }
244 }
245 
246 void ConfigAmqpClient::set_connected(bool connected) {
247  connection_status_ = connected;
249 }
250 
251 void ConfigAmqpClient::GetConnectionInfo(ConfigAmqpConnInfo &conn_info) const {
252  conn_info.connection_status = connection_status_;
253  conn_info.connection_status_change_at =
255  conn_info.url = FormAmqpUri(true);
256 }
257 
258 bool ConfigAmqpClient::ProcessMessage(const string &json_message) {
259  Document document;
260  document.Parse<0>(json_message.c_str());
261 
262  if (document.HasParseError()) {
263  size_t pos = document.GetErrorOffset();
264  // GetParseError returns const char *
265  cout << "Error in parsing JSON message from rabbitMQ at "
266  << pos << "with error description"
267  << document.GetParseError() << endl;
268  return false;
269  } else {
270  string oper = "";
271  string uuid_str = "";
272  string obj_type = "";
273  string obj_name = "";
274  for (Value::ConstMemberIterator itr = document.MemberBegin();
275  itr != document.MemberEnd(); ++itr) {
276  string key(itr->name.GetString());
277  if (key == "oper") {
278  oper = itr->value.GetString();
279  } else if (key == "type") {
280  obj_type = itr->value.GetString();
281  } else if (key == "fq_name") {
282  if (!itr->value.IsArray())
283  continue;
284  ostringstream os;
285  SizeType sz = itr->value.GetArray().Size();
286  if (sz == 0)
287  continue;
288  for (SizeType i = 0; i < sz-1; i++) {
289  os << itr->value[i].GetString() << ":";
290  }
291  os << itr->value[sz-1].GetString();
292  obj_name = os.str();
293  } else if (key == "uuid") {
294  uuid_str = itr->value.GetString();
295  }
296  }
297 
298  if ((oper == "") || (uuid_str == "") || (obj_type == "")) {
299  CONFIG_CLIENT_WARN(ConfigClientFQNameCache,
300  "Empty object name or empty type or empty uuid", obj_type,
301  obj_name, uuid_str);
302  return false;
303  }
304 
305  if ((oper == "CREATE") || (oper == "UPDATE")) {
306  if (obj_name.empty()) {
307  CONFIG_CLIENT_WARN(ConfigClientFQNameCache,
308  "Empty object name during CREATE/UPDATE",
309  obj_type, obj_name, uuid_str);
310  return false;
311  }
312 
313  // It is possible in some cases that RabbitMQ might club the
314  // CREATE and UPDATE for an object if they happen in quick
315  // succession (for instance control node failover). In such
316  // cases, we could only get an UPDATE of the object without
317  // a preceding CREATE. Handle the UPDATE as a CREATE and add
318  // object to FQNameCache.
319  // In the unlikely event that we do receive a CREATE for the
320  // same object after the UPDATE, we check if the FQNameCache
321  // is already present before adding to it.
322  // Also, it is ok to process the CREATE/UPDATE irrespective
323  // of the order in which they are received since we always
324  // read the uuid table from Cassandra.
325 
326  string stored_fq_name =
328  if (stored_fq_name == "ERROR") {
329  // FQName Cache entry not present. Create one.
330  // Log the event if the operation is an UPDATE.
331  if (oper == "UPDATE") {
332  CONFIG_CLIENT_WARN(ConfigClientFQNameCache,
333  "FQ Name Cache entry not found on UPDATE:",
334  obj_type, obj_name, uuid_str);
335  }
337  AddFQNameCache(uuid_str, obj_type, obj_name);
338  }
339  } else if (oper == "DELETE") {
341  InvalidateFQNameCache(uuid_str);
342  }
343 
344  CONFIG_CLIENT_RABBIT_MSG_TRACE(ConfigClientRabbitMQMsgTrace, oper,
345  obj_type, obj_name, uuid_str);
346  EnqueueUUIDRequest(oper, obj_type, uuid_str);
347  }
348  return true;
349 }
350 
352  AmqpClient::Envelope::ptr_t &envelope) {
353  try {
354  // timeout = 10ms.. To handle SIGHUP on config changes
355  // On reinit, config client manager will trigger the amqp client
356  // to shutdown. Blocking wait without timeout will not allow this.
357  channel_->BasicConsumeMessage(consumer_tag_, envelope, 10);
358  return true;
359  } catch (std::exception &e) {
360  static string what = e.what();
361  string message =
362  "RabbitMQ SM: Caught exception while receiving "
363  "messages from RabbitMQ: "
364  + amqpclient_->rabbitmq_ip() + ":"
365  + amqpclient_->rabbitmq_port() + " : " + what;
366  cout << message << endl;
367  CONFIG_CLIENT_WARN(ConfigClientMgrWarning, message);
368  return false;
369  } catch (...) {
370  string message =
371  "RabbitMQ SM: Caught fatal unknown exception while receiving "
372  "messages from RabbitMQ "
373  + amqpclient_->rabbitmq_ip() + ':'
374  + amqpclient_->rabbitmq_port();
375  cout << message << endl;
376  CONFIG_CLIENT_WARN(ConfigClientMgrWarning, message);
377  assert(0);
378  }
379  return true;
380 }
381 
383  AmqpClient::Envelope::ptr_t &envelope) {
384  try {
385  channel_->BasicAck(envelope);
386  } catch (std::exception &e) {
387  static string what = e.what();
388  string message =
389  "RabbitMQ SM: Caught exception while acking "
390  "messages from RabbitMQ: "
391  + amqpclient_->rabbitmq_ip() + ':'
392  + amqpclient_->rabbitmq_port() + ':' + what;
393  cout << message << endl;
394  CONFIG_CLIENT_WARN(ConfigClientMgrWarning, message);
395  return false;
396  } catch (...) {
397  string message =
398  "RabbitMQ SM: Caught fatal unknown exception while acking messages "
399  "from RabbitMQ " + amqpclient_->rabbitmq_ip() + ':'
400  + amqpclient_->rabbitmq_port();
401  cout << message << endl;
402  CONFIG_CLIENT_WARN(ConfigClientMgrWarning, message);
403  assert(0);
404  }
405  return true;
406 }
407 
408 
410  // If reinit is triggerred, don't wait for end of config trigger
411  // return from here to process reinit
412  if (amqpclient_->config_manager()->is_reinit_triggered()) {
414  ConfigClientMgrDebug,
415  "RabbitMQ SM: Reinit triggered, don't wait for end of config");
416  return true;
417  }
418 
419  // To start consuming the message, we should have finised bulk sync
420  amqpclient_->config_manager()->WaitForEndOfConfig();
421 
422  while (true) {
423  // Test only
424  if (amqpclient_->terminate())
425  break;
426  // If reinit is triggerred, break from the message receiving loop
427  if (amqpclient_->config_manager()->is_reinit_triggered()) {
428  CONFIG_CLIENT_DEBUG(ConfigClientMgrDebug,
429  "RabbitMQ SM: Reinit triggered, break from message receiving loop");
430  break;
431  }
432  AmqpClient::Envelope::ptr_t envelope;
433  if (ReceiveRabbitMessages(envelope) == false) {
434  ConnectToRabbitMQ(false);
435  continue;
436  }
437 
438  if (!envelope)
439  continue;
440 
441  amqpclient_->ProcessMessage(envelope->Message()->Body());
442  if (AckRabbitMessages(envelope) == false) {
443  ConnectToRabbitMQ(false);
444  continue;
445  }
446  }
447  return true;
448 }
IpAddress AddressFromString(const std::string &ip_address_str, boost::system::error_code *ec)
boost::scoped_ptr< ConfigAmqpChannel > channel_
bool AckRabbitMessages(AmqpClient::Envelope::ptr_t &envelop)
virtual bool Run()
Code to execute in a task. Returns true if task is completed. Return false to reschedule the task.
RabbitMQReader(ConfigAmqpClient *amqpclient)
string Description() const
Gives a description of the task.
bool ReceiveRabbitMessages(AmqpClient::Envelope::ptr_t &envelop)
void ConnectToRabbitMQ(bool queue_delete=true)
std::string FormAmqpUri(bool hide_auth_info) const
std::string rabbitmq_port() const
std::string rabbitmq_vhost() const
ConfigAmqpClient(ConfigClientManager *mgr, std::string hostname, std::string module_name, const ConfigClientOptions &options)
ConfigClientManager * mgr_
boost::asio::ip::tcp::endpoint Endpoint
void GetConnectionInfo(ConfigAmqpConnInfo &info) const
bool ProcessMessage(const std::string &json_message)
std::vector< Endpoint > endpoints() const
bool rabbitmq_use_ssl() const
void EnqueueUUIDRequest(std::string oper, std::string obj_type, std::string uuid_str)
std::string hostname() const
std::string rabbitmq_ip() const
void increment_rabbitmq_server_index()
void set_connected(bool connected)
std::atomic< bool > connection_status_
void ReportRabbitMQConnectionStatus(bool connected) const
std::vector< std::string > rabbitmq_ports_
std::string rabbitmq_user() const
std::atomic< uint64_t > connection_status_change_at_
std::string rabbitmq_ssl_keyfile() const
std::string rabbitmq_ssl_ca_certs() const
std::string rabbitmq_ssl_certfile() const
size_t rabbitmq_server_list_len() const
std::vector< std::string > rabbitmq_ips_
std::vector< Endpoint > endpoints_
ConfigClientManager * config_manager() const
std::string module_name() const
std::string rabbitmq_password() const
void EnqueueUUIDRequest(std::string oper, std::string obj_type, std::string uuid_str)
ConfigDbClient * config_db_client() const
ConfigJsonParserBase * config_json_parser()
virtual std::string FindFQName(const std::string &uuid) const
const bool IsReadObjectType(std::string objectType)
The TaskScheduler keeps track of what tasks are currently schedulable. When a task is enqueued it is ...
Definition: task.h:307
int GetTaskId(const std::string &name)
Definition: task.cc:884
void Enqueue(Task *task)
Enqueues a task for running. Starts task if all policy rules are met else puts task in waitq....
Definition: task.cc:662
static TaskScheduler * GetInstance()
Definition: task.cc:574
Task is a class to describe a computational task within OpenSDN control plane applications....
Definition: task.h:82
static ConnectionState * GetInstance()
#define CONFIG_CLIENT_RABBIT_MSG_TRACE(obj,...)
#define CONFIG_CLIENT_DEBUG(obj,...)
#define CONFIG_CLIENT_WARN(obj,...)
static int compare(const Type &lhs, const Type &rhs)
bool stringToInteger(const std::string &str, NumberType &num)
Definition: string_util.h:72
Definition: task_int.h:11
boost::tokenizer< boost::char_separator< char > > tokenizer
static std::string UTCUsecToString(uint64_t tstamp)
Definition: time_util.h:55
static uint64_t UTCTimestampUsec()
Definition: time_util.h:14