-
Notifications
You must be signed in to change notification settings - Fork 390
/
config_amqp_client.cc
298 lines (264 loc) · 10.4 KB
/
config_amqp_client.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
/*
* Copyright (c) 2017 Juniper Networks, Inc. All rights reserved.
*/
#include "config_amqp_client.h"
#include <boost/algorithm/string/find.hpp>
#include <stdio.h>
#include <SimpleAmqpClient/SimpleAmqpClient.h>
#include "rapidjson/document.h"
#include <sandesh/sandesh_types.h>
#include <sandesh/sandesh.h>
#include "base/connection_info.h"
#include "base/task.h"
#include "base/string_util.h"
#include "ifmap/ifmap_config_options.h"
#include "ifmap/ifmap_server_show_types.h"
#include "config_cassandra_client.h"
#include "config_client_manager.h"
#include "config_db_client.h"
using namespace boost;
using namespace std;
using namespace contrail_rapidjson;
bool ConfigAmqpClient::disable_;
class ConfigAmqpClient::RabbitMQReader : public Task {
public:
RabbitMQReader(ConfigAmqpClient *amqpclient)
: Task(amqpclient->reader_task_id()), amqpclient_(amqpclient) {
}
virtual bool Run();
string Description() const { return "ConfigAmqpClient::RabbitMQReader"; }
private:
ConfigAmqpClient *amqpclient_;
AmqpClient::Channel::ptr_t channel_;
string consumer_tag_;
bool ConnectToRabbitMQ(bool queue_delete = true);
bool AckRabbitMessages(AmqpClient::Envelope::ptr_t &envelop);
bool ReceiveRabbitMessages(AmqpClient::Envelope::ptr_t &envelop);
};
ConfigAmqpClient::ConfigAmqpClient(ConfigClientManager *mgr, string hostname,
string module_name, const IFMapConfigOptions &options) :
mgr_(mgr), hostname_(hostname), module_name_(module_name),
current_server_index_(0), rabbitmq_user_(options.rabbitmq_user),
rabbitmq_password_(options.rabbitmq_password),
rabbitmq_vhost_(options.rabbitmq_vhost),
rabbitmq_use_ssl_(options.rabbitmq_use_ssl),
rabbitmq_ssl_version_(options.rabbitmq_ssl_version),
rabbitmq_ssl_keyfile_(options.rabbitmq_ssl_keyfile),
rabbitmq_ssl_certfile_(options.rabbitmq_ssl_certfile),
rabbitmq_ssl_ca_certs_(options.rabbitmq_ssl_ca_certs) {
connection_status_ = false;
connection_status_change_at_ = UTCTimestampUsec();
if (disable_)
return;
if (options.rabbitmq_server_list.empty())
return;
for (vector<string>::const_iterator iter =
options.rabbitmq_server_list.begin();
iter != options.rabbitmq_server_list.end(); iter++) {
string server_info(*iter);
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> sep(":");
tokenizer tokens(server_info, sep);
tokenizer::iterator tit = tokens.begin();
string ip(*tit);
rabbitmq_ips_.push_back(ip);
++tit;
string port_str(*tit);
rabbitmq_ports_.push_back(port_str);
}
boost::system::error_code ec;
int port = 0;
stringToInteger(rabbitmq_port(), port);
endpoint_.address(boost::asio::ip::address::from_string(rabbitmq_ip(), ec));
endpoint_.port(port);
TaskScheduler *scheduler = TaskScheduler::GetInstance();
reader_task_id_ = scheduler->GetTaskId("amqp::RabbitMQReader");
Task *task = new RabbitMQReader(this);
scheduler->Enqueue(task);
}
ConfigAmqpClient::~ConfigAmqpClient() {
}
void ConfigAmqpClient::EnqueueUUIDRequest(string oper, string obj_type,
string uuid_str) {
mgr_->EnqueueUUIDRequest(oper, obj_type, uuid_str);
}
string ConfigAmqpClient::FormAmqpUri() const {
string uri = string("amqp://" + rabbitmq_user() + ":" + rabbitmq_password() +
"@" + rabbitmq_ip() + ":" + rabbitmq_port());
if (rabbitmq_vhost() != "") {
uri += "/" + rabbitmq_vhost();
}
return uri;
}
bool ConfigAmqpClient::RabbitMQReader::ConnectToRabbitMQ(bool queue_delete) {
// Update connection info
process::ConnectionState::GetInstance()->Update(
process::ConnectionType::DATABASE, "RabbitMQ",
process::ConnectionStatus::DOWN,
amqpclient_->endpoint(), "RabbitMQ connection down");
amqpclient_->set_connected(false);
while (true) {
string uri = amqpclient_->FormAmqpUri();
try {
channel_ = AmqpClient::Channel::CreateFromUri(uri);
// passive = false, durable = false, auto_delete = false
channel_->DeclareExchange("vnc_config.object-update",
AmqpClient::Channel::EXCHANGE_TYPE_FANOUT, false, false, false);
string queue_name =
amqpclient_->module_name() + "." + amqpclient_->hostname();
if (queue_delete) {
channel_->DeleteQueue(queue_name, true, true);
}
// passive = false, durable = false,
// exclusive = true, auto_delete = false
string queue = channel_->DeclareQueue(queue_name, false, false,
true, false);
channel_->BindQueue(queue, "vnc_config.object-update");
// no_local = true, no_ack = false,
// exclusive = true, message_prefetch_count = 0
consumer_tag_ = channel_->BasicConsume(queue, queue_name,
true, false, true, 0);
} catch (std::exception &e) {
static std::string what = e.what();
std::cout << "Caught fatal exception while connecting to RabbitMQ: "
<< what << std::endl;
// Wait to reconnect
sleep(5);
continue;
} catch (...) {
std::cout << "Caught fatal unknown exception while connecting to "
<< "RabbitMQ: " << std::endl;
assert(0);
}
// Update connection info
process::ConnectionState::GetInstance()->Update(
process::ConnectionType::DATABASE, "RabbitMQ",
process::ConnectionStatus::UP,
amqpclient_->endpoint(), "RabbitMQ connection established");
amqpclient_->set_connected(true);
return true;
}
return false;
}
void ConfigAmqpClient::set_connected(bool connected) {
connection_status_ = connected;
connection_status_change_at_ = UTCTimestampUsec();
}
void ConfigAmqpClient::GetConnectionInfo(ConfigAmqpConnInfo &conn_info) const {
conn_info.connection_status = connection_status_;
conn_info.connection_status_change_at = connection_status_change_at_;
conn_info.url = FormAmqpUri();
}
bool ConfigAmqpClient::ProcessMessage(const string &json_message) {
Document document;
document.Parse<0>(json_message.c_str());
if (document.HasParseError()) {
size_t pos = document.GetErrorOffset();
// GetParseError returns const char *
std::cout << "Error in parsing JSON message from rabbitMQ at "
<< pos << "with error description"
<< document.GetParseError() << std::endl;
return false;
} else {
string oper = "";
string uuid_str = "";
string obj_type = "";
string obj_name = "";
for (Value::ConstMemberIterator itr = document.MemberBegin();
itr != document.MemberEnd(); ++itr) {
string key(itr->name.GetString());
if (key == "oper") {
oper = itr->value.GetString();
} else if (key == "type") {
obj_type = itr->value.GetString();
} else if (key == "obj_dict") {
ostringstream os;
if (!itr->value.HasMember("fq_name"))
continue;
if (!itr->value["fq_name"].IsArray())
continue;
size_t sz = itr->value["fq_name"].GetArray().Size();
for (size_t i=0; i<sz; i++) {
if (!itr->value["fq_name"][SizeType(i)].IsString())
continue;
os << itr->value["fq_name"][SizeType(i)].GetString();
if (i < sz-1)
os << ":";
}
obj_name = os.str();
} else if (key == "uuid") {
uuid_str = itr->value.GetString();
}
}
if ((oper == "") || (uuid_str == "") || (obj_type == "")) {
assert(0);
}
if (oper == "CREATE") {
assert(obj_name != "");
config_manager()->config_db_client()->AddFQNameCache(uuid_str,
obj_name);
}
EnqueueUUIDRequest(oper, obj_type, uuid_str);
}
return true;
}
bool ConfigAmqpClient::RabbitMQReader::ReceiveRabbitMessages(
AmqpClient::Envelope::ptr_t &envelope) {
// To start consuming the message, we should have finised bulk sync
amqpclient_->config_manager()->WaitForEndOfConfig();
try {
// timeout = -1.. wait forever
return (channel_->BasicConsumeMessage(consumer_tag_, envelope, -1));
} catch (std::exception &e) {
static std::string what = e.what();
std::cout << "Caught fatal exception while receiving " <<
"messages from RabbitMQ: " << what << std::endl;
return false;
} catch (...) {
std::cout << "Caught fatal unknown exception while receiving " <<
"messages from RabbitMQ: " << std::endl;
assert(0);
}
return true;
}
bool ConfigAmqpClient::RabbitMQReader::AckRabbitMessages(
AmqpClient::Envelope::ptr_t &envelope) {
try {
channel_->BasicAck(envelope);
} catch (std::exception &e) {
static std::string what = e.what();
std::cout << "Caught fatal exception while Acking message to RabbitMQ: "
<< what << std::endl;
return false;
} catch (...) {
std::cout << "Caught fatal unknown exception while acking messages " <<
"from RabbitMQ: " << std::endl;
assert(0);
}
return true;
}
bool ConfigAmqpClient::RabbitMQReader::Run() {
assert(ConnectToRabbitMQ());
while (true) {
AmqpClient::Envelope::ptr_t envelope;
if (ReceiveRabbitMessages(envelope) == false) {
assert(ConnectToRabbitMQ(false));
continue;
}
amqpclient_->ProcessMessage(envelope->Message()->Body());
if (AckRabbitMessages(envelope) == false) {
assert(ConnectToRabbitMQ(false));
continue;
}
}
return true;
}
int ConfigAmqpClient::reader_task_id() const {
return reader_task_id_;
}
string ConfigAmqpClient::hostname() const {
return hostname_;
}
string ConfigAmqpClient::module_name() const {
return module_name_;
}