-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmsgflo.cpp
More file actions
581 lines (480 loc) · 16.7 KB
/
msgflo.cpp
File metadata and controls
581 lines (480 loc) · 16.7 KB
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
#include "msgflo.h"
#include <iostream>
#include <thread>
#include "amqpcpp.h"
#include "amqpcpp/libev.h"
#include "mqtt_support.h"
using namespace std;
using namespace trygvis::mqtt_support;
namespace msgflo {
std::string random_string( size_t length )
{
auto randchar = []() -> char
{
const char charset[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
const size_t max_index = (sizeof(charset) - 1);
return charset[ rand() % max_index ];
};
std::string str(length,0);
std::generate_n( str.begin(), length, randchar );
return str;
}
int64_t millis_monotonic(void)
{
struct timespec spec;
clock_gettime(CLOCK_MONOTONIC, &spec);
const int64_t ms = (spec.tv_sec*1000) + round(spec.tv_nsec / 1.0e6);
return ms;
}
std::string string_to_upper_copy(const std::string &str) {
std::string ret;
ret.resize(str.size());
for (uint i=0; i<str.size(); i++) {
ret[i] = toupper(str[i]);
}
return ret;
}
bool string_starts_with(const std::string &str, const std::string &prefix) {
return str.substr(0, prefix.size()) == prefix;
}
class DiscoveryMessage {
public:
DiscoveryMessage(const Definition &def)
: definition(def) {
}
json11::Json to_json() const {
using namespace json11;
return Json::object {
{"protocol", "discovery"},
{"command", "participant"},
{"payload", definition.to_json() },
};
}
private:
Definition definition;
};
void defaultMessageHandler(msgflo::Message *msg) {
cout << "Warning: No message handler defined for msgflo::Participant" << endl;
}
template<typename Engine_t>
struct ParticipantRegistrationT : public Participant {
Engine_t *engine;
const std::vector<Definition::Port> inports;
const std::vector<Definition::Port> outports;
const string id;
MessageHandler handler;
const DiscoveryMessage discoveryMessage;
ParticipantRegistrationT(Engine_t *engine, const Definition &definition)
: engine(engine)
, inports(definition.inports)
, outports(definition.outports)
, id(generateId(definition))
, handler(defaultMessageHandler)
, discoveryMessage(definition)
{}
void onMessage(const MessageHandler &h) {
handler = h;
}
virtual void send(std::string port, const json11::Json &json) override {
send(port, json.dump());
}
virtual void send(std::string port, const std::string &string) override {
send(port, string.c_str(), string.size());
}
virtual void send(std::string port, const char *data, uint64_t len) override {
engine->send(this, port, data, len);
}
const Definition::Port *findOutPort(const string &id) const {
for (auto &p: outports) {
if (p.id == id) {
return &p;
}
}
return nullptr;
}
static string generateId(const Definition &d) {
return d.role + std::to_string(rand());
}
};
class AbstractMessage : public Message {
protected:
AbstractMessage(const char *data, const uint64_t len, const std::string &port)
: _data(data)
, _len(len)
, _port(port)
{}
virtual ~AbstractMessage() {};
const char *_data;
const uint64_t _len;
const std::string _port;
public:
virtual void data(const char **data, uint64_t *len) override {
*data = this->_data;
*len = this->_len;
}
virtual std::string port() override {
return _port;
}
virtual std::string asString() override {
string str(_data, _len);
return str;
}
virtual json11::Json asJson() override {
string err;
string str(_data, _len);
auto x = json11::Json::parse(str, err);
if (!err.empty()) {
cerr << "_data=" << _data << endl;
cerr << "_len=" << _len << endl;
throw domain_error("Could not parse JSON body: " + err + ", payload: " + str);
}
return x;
}
};
template<typename EngineType>
class AbstractEngine {
protected:
using ParticipantRegistration = ParticipantRegistrationT<EngineType>;
Definition validateDefinitionFromUser(const Definition &definition) {
Definition d(definition);
if (d.id.size() == 0) {
d.id = d.role + "-" + random_string(8);
}
for (auto &port : d.inports) {
if (port.queue.empty()) {
port.queue = generateQueueName(definition, port);
}
}
for (auto &port : d.outports) {
if (port.queue.empty()) {
port.queue = generateQueueName(definition, port);
}
}
return d;
}
virtual string generateQueueName(const Definition &d, const Definition::Port &) = 0;
vector<ParticipantRegistration> registrations;
};
// C-style subclassing
// used to pass context for libev timer callback
struct EvTimerWrapper {
public:
struct ev_timer timer;
std::function<void (void)> callback;
};
static void timeout_cb(struct ev_loop *loop, ev_timer *timer, int revent) {
EvTimerWrapper *wrapper = (EvTimerWrapper *)timer;
if (wrapper->callback) {
wrapper->callback();
}
}
class AmqpEngine final : public Engine, protected AbstractEngine<AmqpEngine> {
struct AmqpMessage final : public AbstractMessage {
AmqpMessage(AMQP::Channel &channel, uint64_t deliveryTag, const AMQP::Message &m, const std::string &p)
: AbstractMessage(m.body(), m.bodySize(), p)
, _deliveryTag(deliveryTag)
,channel(channel)
{
}
uint64_t _deliveryTag;
AMQP::Channel &channel;
virtual void ack() override {
channel.ack(_deliveryTag);
}
virtual void nack() override {
channel.reject(_deliveryTag);
}
};
public:
AmqpEngine(const string &url, EngineConfig config)
: Engine()
, loop(EV_DEFAULT)
, handler(loop)
, connection(&handler, AMQP::Address(url))
, channel(&connection)
, discoveryPeriod(config.discoveryPeriod/3)
{
channel.setQos(1); // TODO: is this prefech?
channel.onReady([&]() {
connected = true;
for(auto &r: registrations) {
for (const auto &port : r.inports) {
setupInPort(r, port);
}
for (const auto &port : r.outports) {
setupOutPort(port);
}
sendDiscoveryMessage(r);
}
});
}
virtual Participant *registerParticipant(const Definition &definition) override {
Definition d = validateDefinitionFromUser(definition);
registrations.emplace_back(this, d);
return ®istrations[registrations.size() - 1];
}
virtual void launch() override {
discoveryTimer.callback = [this]() {
if (not connected) {
return;
}
for(auto &r: registrations) {
this->sendDiscoveryMessage(r);
}
};
ev_timer_init(&discoveryTimer.timer, timeout_cb, discoveryPeriod, discoveryPeriod);
ev_timer_start(loop, &discoveryTimer.timer);
ev_run(loop, 0);
}
protected:
string generateQueueName(const Definition &d, const Definition::Port &port) override {
return d.role + "." + string_to_upper_copy(port.id);
}
private:
void sendDiscoveryMessage(const ParticipantRegistration &r) {
string data = json11::Json(r.discoveryMessage).dump();
AMQP::Envelope env(data);
channel.publish("", "fbp", env);
}
void setupOutPort(const Definition::Port &p) {
channel.declareExchange(p.queue, AMQP::fanout);
}
void setupInPort(const ParticipantRegistration &r, const Definition::Port &port) {
channel.declareQueue(port.queue, AMQP::durable);
channel.consume(port.queue).onReceived(
[r, this, port](const AMQP::Message &message,
uint64_t deliveryTag,
bool redelivered) {
AmqpMessage msg(channel, deliveryTag, message, port.id);
r.handler(&msg);
});
}
public:
void send(const ParticipantRegistration *r, const string &portName, const char *data, uint64_t size) {
auto p = r->findOutPort(portName);
if (p == nullptr) {
throw domain_error("Unknown out port: " + portName);
}
AMQP::Envelope env(data, size);
cout << " Sending on id=" << p->id << ", queue=" << p->queue << endl;
channel.publish(p->queue, "", env);
}
private:
struct ev_loop *loop;
AMQP::LibEvHandler handler;
AMQP::TcpConnection connection;
AMQP::TcpChannel channel;
int64_t discoveryPeriod;
EvTimerWrapper discoveryTimer;
bool connected = false;
};
using msg_flo_mqtt_client = mqtt_client<trygvis::mqtt_support::mqtt_client_personality::polling>;
class MosquittoEngine final : public Engine, protected mqtt_event_listener, protected AbstractEngine<MosquittoEngine> {
struct MosquittoMessage final : public AbstractMessage {
MosquittoMessage(const struct mosquitto_message *m, bool d, const std::string &p)
: AbstractMessage(static_cast<char *>(m->payload), static_cast<uint64_t>(m->payloadlen), p)
, _mid(m->mid)
, _debugOutput(d)
{
}
int _mid;
bool _debugOutput = false;
virtual void ack() override {
if (_debugOutput) {
cerr << "MosquittoMessage.ack() is currently a no-op" << endl;
}
}
virtual void nack() override {
if (_debugOutput) {
cerr << "MosquittoMessage.nack() is currently a no-op" << endl;
}
}
};
public:
MosquittoEngine(const EngineConfig config, const string &host, const int port,
const int keep_alive, const string &client_id, const bool clean_session, const std::string &user, const std::string &pw)
: _debugOutput(config.debugOutput())
, client(this, host, port, keep_alive, client_id, clean_session)
, discoveryLastSent(0)
, discoveryPeriod(config.discoveryPeriod/3)
{
if (user.size()) {
client.setUsernamePassword(user, pw);
}
client.connect();
}
virtual ~MosquittoEngine() {
}
virtual Participant *registerParticipant(const Definition &definition) override {
Definition d = validateDefinitionFromUser(definition);
registrations.emplace_back(this, d);
return ®istrations[registrations.size() - 1];
}
void send(const ParticipantRegistration *r, const string &portName, const char *data, uint64_t len) {
auto port = r->findOutPort(portName);
if (port == nullptr) {
throw domain_error("No such port: " + portName);
}
client.publish(nullptr, port->queue, 0, false, static_cast<int>(len), data);
}
virtual void launch() override {
run = true;
while (run) {
const auto t = millis_monotonic()/1000;
if (connected and (t - discoveryLastSent) > discoveryPeriod) {
for(auto &r: registrations) {
sendDiscoveryMessage(r);
}
discoveryLastSent = t;
}
client.poll();
}
}
protected:
string generateQueueName(const Definition &d, const Definition::Port &port) override {
return d.role + "." + string_to_upper_copy(port.id);
}
virtual void on_msg(const string &msg) override {
if (!_debugOutput) {
return;
}
cout << "mqtt: " << msg << endl;
}
virtual void on_message(const struct mosquitto_message *message) override {
string topic = message->topic;
for (auto &r : registrations) {
for (auto &p : r.inports) {
if (p.queue == topic) {
MosquittoMessage m(message, _debugOutput, p.id);
r.handler(&m);
}
}
}
}
virtual void on_connect(int rc) override {
connected = true;
for(auto &r: registrations) {
for (auto &p : r.inports) {
on_msg("Connecting port " + p.id + " to mqtt topic " + p.queue);
client.subscribe(nullptr, p.queue, 0);
}
sendDiscoveryMessage(r);
}
discoveryLastSent = millis_monotonic()/1000;
}
private:
void sendDiscoveryMessage(const ParticipantRegistration &r) {
const string data = json11::Json(r.discoveryMessage).dump();
client.publish(nullptr, "fbp", 0, false, data);
}
private:
const bool _debugOutput;
atomic_bool run;
msg_flo_mqtt_client client;
vector<ParticipantRegistration> registrations;
bool connected;
int64_t discoveryLastSent;
const int64_t discoveryPeriod;
};
shared_ptr<Engine> createEngine(const EngineConfig config) {
string url = config.url();
if (url.empty()) {
const char* broker = std::getenv("MSGFLO_BROKER");
if (broker) {
url = broker;
}
}
if (url.empty()) {
throw invalid_argument("Missing msgflo url and MSGFLO_BROKER is not set.");
}
if (string_starts_with(url, "mqtt://")) {
string host, username, password;
int port = 1883;
int keep_alive = 180;
string client_id;
bool clean_session = true;
string s = url.substr(7);
auto i_up = s.find('@');
if (i_up != string::npos) {
string up = s.substr(0, i_up);
// cout << "up: " << up << endl;
auto i_u = up.find(':');
if (i_u != string::npos) {
username = up.substr(0, i_u);
password = up.substr(i_u + 1);
} else {
username = up;
}
// cout << "username: " << username << endl;
// cout << "password: " << password << endl;
s = s.substr(i_up + 1);
// cout << "s: " << s << endl;
}
auto i_q = s.find('?');
if (i_q != string::npos) {
host = s.substr(0, i_q);
s = s.substr(i_q + 1);
// cout << "s: " << s << endl;
while (!s.empty()) {
auto i_amp = s.find('&');
string kv;
if (i_amp == string::npos) {
kv = s;
s = "";
} else {
kv = s.substr(0, i_amp);
}
// cout << "kv: " << kv << endl;
auto i_eq = kv.find('=');
string key, value;
if (i_eq != string::npos) {
key = kv.substr(0, i_eq);
value = kv.substr(i_eq + 1);
} else {
key = kv;
}
// cout << "key: " << key << endl;
if (key == "keepAlive") {
try {
auto v = stoul(value);
if (v > INT_MAX) {
throw invalid_argument("too big");
}
keep_alive = static_cast<int>(v);
} catch (invalid_argument &e) {
throw invalid_argument("Bad keepAlive argument, must be a number greater than zero.");
} catch (out_of_range &e) {
throw invalid_argument("Bad keepAlive argument, must be a number greater than zero.");
}
} else if (key == "clientId") {
client_id = value;
} else if (key == "cleanSession") {
clean_session = !(value == "0" || value == "no" || value == "false");
} else {
// ignore unknown keys
}
if (i_amp == string::npos) {
break;
}
s = s.substr(i_amp + 1);
// cout << "s: " << s << endl;
}
} else {
host = s;
}
if (config.debugOutput()) {
cout << "host: " << host << endl;
cout << "client_id: " << client_id << endl;
cout << "keep_alive: " << keep_alive << endl;
cout << "clean_session: " << clean_session << endl;
}
return make_shared<MosquittoEngine>(config, host, port, keep_alive, client_id, clean_session, username, password);
} else if (string_starts_with(url, "amqp://")) {
return make_shared<AmqpEngine>(url, config);
}
throw std::runtime_error("Unsupported URL scheme: " + url);
}
} // namespace msgflo