-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathReceiveSQL.cpp
More file actions
executable file
·2194 lines (1763 loc) · 78.8 KB
/
ReceiveSQL.cpp
File metadata and controls
executable file
·2194 lines (1763 loc) · 78.8 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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* vim:set noexpandtab tabstop=4 wrap filetype=cpp */
#include "ReceiveSQL.h"
#include <exception>
#include <stdio.h>
#include <cstring>
#include <locale> // toupper
// TODO: invoking pg_promote requires either superuser privileges, or explicit granting
// of EXECUTE on the function pg_promote. We should grant this to the middleman,
// which otherwise runs as the toolanalysis user....
// TODO: currently pg_promote is sent to the rundb, with last update time also
// queried from the rundb. But what about the monitoringdb? Does pg_promote
// act on both? We should check. Also, get the newest update time from either.
// TODO: currently Read and Write queries are implicitly sent to the monitoringdb,
// we need to include a variable saying where it should go!!!
// TODO check validity of reinterpret_casts?
// ≫ ──── ≪•◦ ❈ ◦•≫ ──── ≪
// Main Program Parts
// ≫ ──── ≪•◦ ❈ ◦•≫ ──── ≪
bool ReceiveSQL::Initialise(std::string configfile){
Store m_variables;
Log("Reading config",3);
m_variables.Initialise(configfile);
// needs to be done first (or at least before InitZMQ)
Log("Initialising Messaging Queues",3);
get_ok = InitMessaging(m_variables);
if(not get_ok) return false;
Log("Initialising run database",3);
get_ok = InitPostgres(m_variables, "run");
if(not get_ok) return false;
Log("Initialising monitoring database",3);
get_ok = InitPostgres(m_variables, "monitoring");
if(not get_ok) return false;
Log("Initializing ZMQ sockets",3);
get_ok = InitZMQ(m_variables);
if(not get_ok) return false;
Log("Initializing ServiceDiscovery",3);
get_ok = InitServiceDiscovery(m_variables);
if(not get_ok) return false;
return true;
}
bool ReceiveSQL::Execute(){
Log("ReceiveSQL Executing...",5);
// find new clients
Log("Finding new clients",4);
get_ok = FindNewClients();
// poll the input sockets for messages
Log("Polling input sockets",4);
get_ok = zmq::poll(in_polls.data(), in_polls.size(), inpoll_timeout);
if(get_ok<0){
Log("Warning! ReceiveSQL error polling input sockets; have they closed?",0);
}
// receive inputs
if(am_master){
Log("Getting Client Write Queries",4);
get_ok = GetClientWriteQueries();
}
Log("Getting Client Read Queries",4);
get_ok = GetClientReadQueries();
Log("Getting Client Log Messages",4);
get_ok = GetClientLogMessages();
Log("Getting Middleman Checkin",4);
get_ok = GetMiddlemanCheckin();
Log("Checking Master Status",4);
get_ok = CheckMasterStatus();
if(am_master){
Log("Running Next Write Query",4);
get_ok = RunNextWriteQuery();
}
Log("Running Next Read Query",4);
get_ok = RunNextReadQuery();
if(am_master){
Log("Running Next Log Message",4);
get_ok = RunNextLogMsg();
}
// poll the output sockets for listeners
Log("Polling output sockets",4);
get_ok = zmq::poll(out_polls.data(), out_polls.size(), outpoll_timeout);
if(get_ok<0){
Log("Warning! ReceiveSQL error polling output sockets; have they closed?",0);
}
// send outputs
Log("Sending Next Client Response",4);
get_ok = SendNextReply();
Log("Sending Next Log Message",4);
get_ok = SendNextLogMsg();
Log("Broadcasting Presence",4);
get_ok = BroadcastPresence();
// Maintenance
Log("Trimming Write Queue",4);
get_ok = TrimQueue("wrt_txn_queue");
Log("Trimming Read Queue",4);
get_ok = TrimQueue("rd_txn_queue");
Log("Trimming Ack Queue",4);
get_ok = TrimQueue("response_queue");
Log("Trimming In Logging Deque",4);
get_ok = TrimDequeue("in_log_queue");
Log("Trimming Out Logging Deque",4);
get_ok = TrimDequeue("out_log_queue");
Log("Trimming Cache",4);
get_ok = TrimCache();
Log("Cleaning Up Old Cache Messages",4);
get_ok = CleanupCache();
// Monitoring and Logging
Log("Tracking Stats",4);
if(!stats_period.is_negative()) get_ok = TrackStats();
Log("Loop Iteration Done",5);
return true;
}
bool ReceiveSQL::Finalise(){
Log("Closing middleman",3);
// remove our services from those advertised?
Log("Removing Discoverable Services",3);
if(utilities) utilities->RemoveService("middleman");
Log("Deleting Utilities",3);
if(utilities){ delete utilities; utilities=nullptr; }
Log("Deleting ServiceDiscovery",3);
if(service_discovery){ delete service_discovery; service_discovery=nullptr; }
Log("Clearing known connections",3);
clt_rtr_connections.clear();
mm_rcv_connections.clear();
clt_sub_connections.clear();
log_sub_connections.clear();
// delete sockets
Log("Deleting sockets",3);
if(clt_sub_socket){ delete clt_sub_socket; clt_sub_socket=nullptr; }
if(clt_rtr_socket){ delete clt_rtr_socket; clt_rtr_socket=nullptr; }
if(mm_rcv_socket) { delete mm_rcv_socket; mm_rcv_socket=nullptr; }
if(mm_snd_socket) { delete mm_snd_socket; mm_snd_socket=nullptr; }
if(log_sub_socket){ delete log_sub_socket; log_sub_socket=nullptr; }
if(log_pub_socket){ delete log_pub_socket; log_pub_socket=nullptr; }
// delete zmq context
Log("Deleting context",3);
if(context){ delete context; context=nullptr; }
// clear all message queues
Log("Clearing message queues",3);
wrt_txn_queue.clear();
rd_txn_queue.clear();
resp_queue.clear();
cache.clear();
in_log_queue.clear();
out_log_queue.clear();
Log("Done, returning",3);
return true;
}
// ≫ ──── ≪•◦ ❈ ◦•≫ ──── ≪
// Main Subroutines
// ≫ ──── ≪•◦ ❈ ◦•≫ ──── ≪
bool ReceiveSQL::InitPostgres(Store& m_variables, std::string prefix){
// ##########################################################################
// default initialize variables
// ##########################################################################
std::string dbhostname = "/tmp"; // '/tmp' = local unix socket
std::string dbhostaddr = ""; // fallback if hostname is empty, an ip address
int dbport = 5432; // database port
std::string dbuser = ""; // database user to connect as. defaults to PGUSER env var if empty.
std::string dbpasswd = ""; // database password. defaults to PGPASS or PGPASSFILE if not given.
std::string dbname = prefix+"db"; // database name
// on authentication: we may consider using 'ident', which will permit the
// user to connect to the database as the postgres user with name matching
// their OS username, and/or the database user mapped to their username
// with the pg_ident.conf file in postgres database. in such a case dbuser and dbpasswd
// should be left empty
// ##########################################################################
// # Update with user-specified values.
// ##########################################################################
m_variables.Get("hostname",dbhostname);
m_variables.Get("hostaddr",dbhostaddr);
m_variables.Get("port",dbport);
m_variables.Get("user",dbuser);
m_variables.Get("passwd",dbpasswd);
//m_variables.Get(prefix+"name",dbname);
// ##########################################################################
// # Open connection
// ##########################################################################
// pass connection details to the postgres interface class
Postgres* interface;
if(prefix=="run"){
interface = &m_rundb;
} else if(prefix=="monitoring"){
interface = &m_monitoringdb;
} else {
Log(Concat("Uknown database prefix ",prefix," in InitPostgres"),0);
return false;
}
interface->Init(dbhostname,
dbhostaddr,
dbport,
dbuser,
dbpasswd,
dbname);
// try to open a connection to ensure we can do, or else bail out now.
get_ok = interface->OpenConnection();
if(not get_ok){
Log(Concat("Error! Failed to open connection to the postgres ",prefix," database!"),0);
return false;
}
return true;
}
// ««-------------- ≪ °◇◆◇° ≫ --------------»»
bool ReceiveSQL::InitZMQ(Store& m_variables){
// ##########################################################################
// # default initialize variables
// ##########################################################################
// the underlying zmq context can use multiple threads if we have really heavy traffic
int context_io_threads = 1;
// we have five zmq sockets:
// 1. [SUB] one for receiving published write queries from clients
// 2. [DEALER] one for receiving dealt read queries from clients
// 3. [ROUTER] one for sending back responses to queries we've run
// 4. [PUB] one for sending messages to the other middleman
// 5. [SUB] one for receiving messages from the other middleman
// 6. [SUB] one for receiving logging messages for the monitoring database, if we're the master.
// 7. [PUB] one for sending logging messages to the other middleman if we're not the master
// the number and types of sockets are dictated by the messaging architecture
// 1. we use SUB because clients send write requests to both middlemen, so they don't need to keep track
// of who is the master. Both middlemen will receive all write requests, but only the master should
// execute them - the standby discards them.
// 2. we use a DEALER to receive read queries since they're round robined by clients, allowing load
// distribution between the master and hot standby.
// 3. we use ROUTER since we need to asynchronously send (or not, as required) acknowledgement replies
// to a specified recipient.
// 4/5. we use a pair of PUB/SUB sockets so that each middleman can broadcast its presence
// without requiring a listener (should the other middleman go down).
// 6/7. we use PUB/SUB so that clients can publish logging messages without worrying about who
// is the master. They won't require a reply.
// specify the ports everything talks on. All listeners connect to the remote port
// which is picked up by ServiceDiscovery
mm_snd_port = 55596; // for sending middleman beacons
log_pub_port = 55554; // for sending logging messages to the master
// socket timeouts, so nothing blocks indefinitely
clt_sub_socket_timeout=500;
int clt_rtr_socket_timeout=500; // used for both sends and receives
int mm_rcv_socket_timeout=500;
int mm_snd_socket_timeout=500;
log_sub_socket_timeout=500;
int log_pub_socket_timeout=500;
// poll timeouts - we can poll multiple sockets at once to consolidate our polling deadtime.
// the poll operation can also be used to prevent the cpu railing.
// we keep the in poll and out poll operations separate as the in poll will always be run,
// whereas the send sockets may not be polled if we have nothing to send.
// (i suppose we could combine them, and poll the output sockets regardless...)
// units are milliseconds
inpoll_timeout=500;
outpoll_timeout=500;
// ##########################################################################
// # Update with user-specified values.
// ##########################################################################
// If not given, default value will be retained.
m_variables.Get("context_io_threads",context_io_threads);
m_variables.Get("mm_snd_port",mm_snd_port);
m_variables.Get("log_pub_port",log_pub_port);
m_variables.Get("clt_sub_socket_timeout",clt_sub_socket_timeout);
m_variables.Get("clt_rtr_socket_timeout",clt_rtr_socket_timeout);
m_variables.Get("mm_rcv_socket_timeout",mm_rcv_socket_timeout);
m_variables.Get("mm_snd_socket_timeout",mm_snd_socket_timeout);
m_variables.Get("log_pub_socket_timeout",log_pub_socket_timeout);
m_variables.Get("log_sub_socket_timeout",log_sub_socket_timeout);
m_variables.Get("inpoll_timeout",inpoll_timeout);
m_variables.Get("outpoll_timeout",outpoll_timeout);
// ##########################################################################
// # Open connections
// ##########################################################################
// open a zmq context
context = new zmq::context_t(context_io_threads);
if(am_master){
// socket to receive published write queries from clients
// -------------------------------------------------------
clt_sub_socket = new zmq::socket_t(*context, ZMQ_SUB);
// this socket never sends, so a send timeout is irrelevant.
clt_sub_socket->setsockopt(ZMQ_RCVTIMEO, clt_sub_socket_timeout);
// don't linger too long, it looks like the program crashed.
clt_sub_socket->setsockopt(ZMQ_LINGER, 10);
clt_sub_socket->setsockopt(ZMQ_SUBSCRIBE,"",0);
// we will connect this socket to clients with the utilities class
}
// socket to receive dealt read queries and send responses to clients
// ------------------------------------------------------------------
clt_rtr_socket = new zmq::socket_t(*context, ZMQ_ROUTER);
clt_rtr_socket->setsockopt(ZMQ_SNDTIMEO, clt_rtr_socket_timeout);
clt_rtr_socket->setsockopt(ZMQ_RCVTIMEO, clt_rtr_socket_timeout);
// don't linger too long, it looks like the program crashed.
clt_rtr_socket->setsockopt(ZMQ_LINGER, 10);
// FIXME remove- for debug only:
// make reply socket error out if the destination is unreachable
// (normally it silently drops the message)
clt_rtr_socket->setsockopt(ZMQ_ROUTER_MANDATORY, 1);
// we'll connect this socket to clients with the utilities class
// socket to listen for presence of the other middleman
// ----------------------------------------------------
mm_rcv_socket = new zmq::socket_t(*context, ZMQ_SUB);
mm_rcv_socket->setsockopt(ZMQ_RCVTIMEO, mm_rcv_socket_timeout);
// this socket never sends, so a send timeout is irrelevant.
// don't linger too long, it looks like the program crashed.
mm_rcv_socket->setsockopt(ZMQ_LINGER, 10);
mm_rcv_socket->setsockopt(ZMQ_SUBSCRIBE,"",0);
// we'll connect this socket to clients with the utilities class
// socket to broadcast our presence to the other middleman
// -------------------------------------------------------
mm_snd_socket = new zmq::socket_t(*context, ZMQ_PUB);
mm_snd_socket->setsockopt(ZMQ_SNDTIMEO, mm_snd_socket_timeout);
// this socket never receives, so a recieve timeout is irrelevant.
// don't linger too long, it looks like the program crashed.
mm_snd_socket->setsockopt(ZMQ_LINGER, 10);
// this one we're a publisher, so we do bind.
mm_snd_socket->bind(std::string("tcp://*:")+std::to_string(mm_snd_port));
// only listen to the logging message port if we're the master
if(am_master){
// socket to receive logging queries for the monitoring db
// -------------------------------------------------------
log_sub_socket = new zmq::socket_t(*context, ZMQ_SUB);
log_sub_socket->setsockopt(ZMQ_RCVTIMEO, log_sub_socket_timeout);
// this socket never sends, so a send timeout is irrelevant.
// don't linger too long, it looks like the program crashed.
log_sub_socket->setsockopt(ZMQ_LINGER, 10);
log_sub_socket->setsockopt(ZMQ_SUBSCRIBE,"",0);
// we'll connect this socket to clients with the utilities class
}
// socket to send log queries to the master, if not us
// ----------------------------------------------------
log_pub_socket = new zmq::socket_t(*context, ZMQ_PUB);
log_pub_socket->setsockopt(ZMQ_SNDTIMEO, log_pub_socket_timeout);
// this socket never receives, so a recieve timeout is irrelevant.
// don't linger too long, it looks like the program crashed.
log_pub_socket->setsockopt(ZMQ_LINGER, 10);
// again we'll bind to this as it's a publisher
log_pub_socket->bind(std::string("tcp://*:")+std::to_string(log_pub_port));
// make items to poll the input and output sockets
zmq::pollitem_t clt_rtr_socket_pollin = zmq::pollitem_t{*clt_rtr_socket,0,ZMQ_POLLIN,0};
zmq::pollitem_t clt_rtr_socket_pollout = zmq::pollitem_t{*clt_rtr_socket,0,ZMQ_POLLOUT,0};
zmq::pollitem_t mm_rcv_socket_pollin = zmq::pollitem_t{*mm_rcv_socket,0,ZMQ_POLLIN,0};
zmq::pollitem_t mm_snd_socket_pollout= zmq::pollitem_t{*mm_snd_socket,0,ZMQ_POLLOUT,0};
zmq::pollitem_t log_pub_socket_pollout= zmq::pollitem_t{*log_pub_socket,0,ZMQ_POLLOUT,0};
// bundle the polls together so we can do all of them at once
in_polls = std::vector<zmq::pollitem_t>{clt_rtr_socket_pollin,
mm_rcv_socket_pollin};
out_polls = std::vector<zmq::pollitem_t>{clt_rtr_socket_pollout,
mm_snd_socket_pollout,
log_pub_socket_pollout};
// if we're the master we have a couple of extras for receiving database writes.
// put them at the end so we can add/remove them as we get promoted/demoted.
if(am_master){
zmq::pollitem_t clt_sub_socket_pollin = zmq::pollitem_t{*clt_sub_socket,0,ZMQ_POLLIN,0};
zmq::pollitem_t log_sub_socket_pollin = zmq::pollitem_t{*log_sub_socket,0,ZMQ_POLLIN,0};
in_polls.push_back(clt_sub_socket_pollin);
in_polls.push_back(log_sub_socket_pollin);
}
return true;
}
bool ReceiveSQL::InitServiceDiscovery(Store& m_variables){
// Use a service discovery class to locate clients.
// Read service discovery configs into a Store
std::string service_discovery_config;
m_variables.Get("service_discovery_config", service_discovery_config);
Store service_discovery_configstore;
service_discovery_configstore.Initialise(service_discovery_config);
// we'll need to send broadcasts to advertise our presence to the other middleman
bool send_broadcasts = true;
// we also need to listen for other service providers - the clients and the other middleman
bool rcv_broadcasts = true;
// multicast address and port to listen for other services on.
std::string broadcast_address = "239.192.1.1";
int broadcast_port = 5000;
service_discovery_configstore.Get("broadcast_address",broadcast_address);
service_discovery_configstore.Get("broadcast_port",broadcast_port);
// how frequently to broadcast - note that we send intermittent messages about our status
// over the mm_snd_port anyway, so the ServiceDiscovery is only used for the initial discovery.
// since we also use the mm_snd_sock and mm_rcv_sock for negotiation, we can't do without them,
// so it's probably not worth trying to move this functionality into the ServiceDiscovery class.
int broadcast_period_sec = 5;
service_discovery_configstore.Get("broadcast_period",broadcast_period_sec);
// whenever we broadcast any services the ServiceDiscovery class automatically advertises
// the presence of a remote control port. It will attempt to check the status of that remote
// control service on each broadcast by querying localhost:remote_control_port.
// For now, unless we implement a listener to respond to those messages,
// the zmq poll will timeout and the reported Status will just be "Status".
// (the RemoteControl Service is normally implemented as part of ToolDAQ)
// for the moment, this is N/A
int remote_control_port = 24011;
// A service name. The Utilities class has a helper function that will connect
// a given zmq socket to all broadcasters with a given service name.
// The name given in the ServiceDiscovery constructor is used for the RemoteControl
// service (which we are not yet using, so N/A for now).
std::string client_name = "Middleman";
service_discovery_configstore.Get("client_name",client_name);
// a unique identifier for us. this is used by the ServiceDiscovery listener thread,
// which maintains a map of services it's recently heard about, for which this is the key.
boost::uuids::uuid client_id = boost::uuids::random_generator()();
// The ServiceDiscovery class maintains a list of services it hears from, but it'll prune
// services that it hasn't heard from after a while so that it doesn't retain stale ones.
// How long before we prune, in seconds
int kick_secs = 30;
service_discovery_configstore.Get("kick_secs",kick_secs);
// construct the ServiceDiscovery instance.
service_discovery = new ServiceDiscovery(send_broadcasts, rcv_broadcasts, remote_control_port,
broadcast_address, broadcast_port, context, client_id,
client_name, broadcast_period_sec, kick_secs);
// it'll handle discovery & broadcasting in a separate thread - we don't need to do anything else.
// version that only listens, doesn't broadcast
//service_discovery = new ServiceDiscovery(broadcast_address, broadcast_port, context, kick_secs);
// Register Services
// -----------------
// to connect our listener ports to the clients discovered with the ServiceDiscovery class
// we can use a Utilities class
utilities = new Utilities(context);
// this lets us connect our listener socket to all clients advertising a given service with:
utilities->UpdateConnections("psql_read", clt_rtr_socket, clt_rtr_connections);
utilities->UpdateConnections("middleman", mm_rcv_socket, mm_rcv_connections);
// additional listening for master on write query and logging ports
if(am_master){
utilities->UpdateConnections("psql_write", clt_sub_socket, clt_sub_connections);
utilities->UpdateConnections("logging", log_sub_socket, log_sub_connections);
}
// we'll call this each Execute loop to connect to any newly found clients.
// we can also register services we wish to broadcast as follows:
utilities->AddService("middleman", mm_snd_port);
if(!am_master){
utilities->AddService("logging",log_pub_port);
}
// note that it is not necessary to register the RemoteControl service,
// this is automatically done by the ServiceDiscovery class.
return true;
}
// ««-------------- ≪ °◇◆◇° ≫ --------------»»
bool ReceiveSQL::InitMessaging(Store& m_variables){
// ##########################################################################
// # default initialize variables
// ##########################################################################
// Master-Standby Messaging
// ------------------------
// time between master-slave check-ins
int broadcast_period_ms = 1000;
// how long we go without a message from the master before we promote ourselves
int promote_timeout_ms = 10000;
// how long before we start logging warnings that the other middleman is lagging.
mm_warn_timeout = 7000;
// are we the master?
am_master = false;
// should we promote ourselves if we can't find the master
dont_promote = false;
// should we warn about missing standby?
warn_no_standby = false;
// Client messaging
// ----------------
// how many times we try to send a response if zmq fails
max_send_attempts = 3;
// how many postgres queries/responses to queue before we start dropping them
warn_limit = 700;
// how many postgres queries/responses to queue before we emit warnings
drop_limit = 1000;
// how long to retain responses in case they get lost, so we can resend them if the client asks
int cache_period_ms = 10000;
// if we get a write query over the dealer port, which should be used for read-only transactions,
// do we just error out, or, if we're the master, do we just run it anyway...?
handle_unexpected_writes = false;
// how often to write out monitoring stats
int stats_period_ms = 60000;
// logging
// -------
stdio_verbosity = 3; // print errors, warnings and messages
db_verbosity = 2; // log to database only errors and warnings
// ##########################################################################
// # Update with user-specified values.
// ##########################################################################
m_variables.Get("broadcast_period_ms",broadcast_period_ms);
m_variables.Get("promote_timeout_ms",promote_timeout_ms);
m_variables.Get("mm_warn_timeout",mm_warn_timeout);
m_variables.Get("am_master",am_master);
m_variables.Get("dont_promote",dont_promote);
m_variables.Get("warn_no_standby",warn_no_standby);
m_variables.Get("max_send_attempts",max_send_attempts);
m_variables.Get("warn_limit",warn_limit);
m_variables.Get("drop_limit",drop_limit);
m_variables.Get("cache_period_ms",cache_period_ms);
m_variables.Get("handle_unexpected_writes",handle_unexpected_writes);
m_variables.Get("stats_period_ms",stats_period_ms);
m_variables.Get("stdio_verbosity",stdio_verbosity);
m_variables.Get("db_verbosity",db_verbosity);
// ##########################################################################
// # Conversions
// ##########################################################################
// convert times to boost for easy handling
broadcast_period = boost::posix_time::milliseconds(broadcast_period_ms);
promote_timeout = boost::posix_time::milliseconds(promote_timeout_ms);
cache_period = boost::posix_time::milliseconds(cache_period_ms);
stats_period = boost::posix_time::milliseconds(stats_period_ms);
boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
last_mm_receipt = now;
last_mm_send = now;
last_stats_calc = now;
return true;
}
// ««-------------- ≪ °◇◆◇° ≫ --------------»»
bool ReceiveSQL::FindNewClients(){
int new_connections=0;
int old_connections=0;
// update any connections
old_connections=clt_rtr_connections.size();
utilities->UpdateConnections("psql_read", clt_rtr_socket, clt_rtr_connections);
new_connections+=clt_rtr_connections.size()-old_connections;
old_connections=mm_rcv_connections.size();
utilities->UpdateConnections("mm_rcv", mm_rcv_socket, mm_rcv_connections);
new_connections+=mm_rcv_connections.size()-old_connections;
// additional listening for master on write query and logging ports
if(am_master){
old_connections=clt_sub_connections.size();
utilities->UpdateConnections("psql_write", clt_sub_socket, clt_sub_connections);
new_connections+=clt_sub_connections.size()-old_connections;
old_connections=log_sub_connections.size();
utilities->UpdateConnections("logging", log_sub_socket, log_sub_connections);
new_connections+=log_sub_connections.size()-old_connections;
}
if(new_connections>0){
Log("Made "+std::to_string(new_connections)+" new connections!",3);
} else {
Log("No new clients found",5);
}
/* needs fixing to uncomment
std::cout<<"We have: "<<connections.size()<<" connected clients"<<std::endl;
std::cout<<"Connections are: "<<std::endl;
for(auto&& athing : connections){
std::string service;
athing.second->Get("msg_value",service);
std::cout<<service<<" connected on "<<athing.first<<std::endl;
}
*/
return true;
}
// ««-------------- ≪ °◇◆◇° ≫ --------------»»
bool ReceiveSQL::GetClientWriteQueries(){
// see if we had any write requests from clients
if(in_polls.at(2).revents & ZMQ_POLLIN){
++write_queries_recvd;
// we did. receive next message.
std::vector<zmq::message_t> outputs;
get_ok = Receive(clt_sub_socket, outputs);
if(not get_ok){
Log(Concat("error receiving part ",outputs.size()+1," of Write query from client"),1);
++write_query_recv_fails;
return false;
}
// received message format should be a 4-part message
// expected parts are:
// 1. ZMQ_IDENTITY of the sender client
// 2. a unique ID used by the sender to match acknowledgements to sent messages
// 3. a database name
// 4. an SQL statement
std::string client_str="-"; uint32_t msg_int=-1; std::string dbname="-";
std::string qry_string="-";
if(outputs.size()>0){
client_str.resize(outputs.at(0).size(),'\0');
memcpy((void*)client_str.data(),outputs.at(0).data(),outputs.at(0).size());
}
if(outputs.size()>1) msg_int = *reinterpret_cast<uint32_t*>(outputs.at(1).data());
if(outputs.size()>2){
dbname.resize(outputs.at(2).size(),'\0');
memcpy((void*)dbname.data(),outputs.at(2).data(),outputs.at(2).size());
}
//if(outputs.size()>3){
// qry_string.resize(outputs.at(3).size(),'\0');
// memcpy((void*)qry_string.data(),outputs.at(3).data(),outputs.at(3).size());
//}
if(outputs.size()!=4){
Log(Concat("unexpected ",outputs.size()," part message in Write query from client"),1);
Log(Concat("client: '",client_str,"', msg_id: ",msg_int,", db: '",dbname,"'"),4);
++write_query_recv_fails;
return false;
}
// to track messages already handled, we form a key from the client ID and message ID,
// and will use this to track message processing
std::pair<std::string, uint32_t> key{client_str,msg_int};
// check if we've received this query before
// 1. we may have this query queued, but haven't run it yet - ignore
// 2. we may have run the query, but not yet sent the response - ignore
// 3. we may have run the query and sent the response, but it got lost in the mail -
// re-add the response to the to-send queue.
// otherwise add to our query queue.
Log(Concat("RECEIVED WRITE QUERY FROM CLIENT '",client_str,"' with msg id ",msg_int),3);
if(cache.count(key)){
std::cout<<"skipping write as we've done it already"<<std::endl;
/*
if(memcmp(outputs.at(0).data(),cache.at(key).client_id.data(),outputs.at(0).size())!=0){
std::cout<<"client id messages are different"<<std::endl;
std::cout<<"old message had length "<<cache.at(key).client_id.size()
<<"new message had length "<<outputs.at(0).size()<<std::endl;
size_t newsize = outputs.at(0).size();
unsigned char* newid = new unsigned char[newsize];
memcpy(newid,outputs.at(0).data(),newsize);
std::cout<<"new id is '";
for(int i=0; i<newsize; ++i){
printf("%02x",newid[i]);
}
std::cout<<"', old id is '";
size_t oldsize = cache.at(key).client_id.size();
unsigned char* oldid = new unsigned char[newsize];
memcpy(oldid,cache.at(key).client_id.data(),newsize);
for(int i=0; i<newsize; ++i){
printf("%02x",oldid[i]);
}
std::cout<<"'"<<std::endl;
}
// override old client id with new cliend id
memcpy(cache.at(key).client_id.data(),outputs.at(0).data(),outputs.at(0).size());
*/
Log("We know this query...",10);
// we've already run and sent the response to this query, resend it.
resp_queue.emplace(key,cache.at(key));
cache.erase(key);
} else if(wrt_txn_queue.count(key)==0 && resp_queue.count(key)==0){
Log("New query, adding to write queue",10);
// we don't have it waiting either in to-run or to-respond queues.
// construct a Query object to encapsulate the query
Query msg{outputs.at(0), outputs.at(1), outputs.at(2), outputs.at(3)};
Log(Concat("QUERY WAS: '",msg.query,"'"),20);
wrt_txn_queue.emplace(key, msg);
} // else we've already got it queued, ignore it.
}// else no messages from clients
/*
else {
std::cout<<"no write queries at input port"<<std::endl;
}
*/
return true;
}
// ««-------------- ≪ °◇◆◇° ≫ --------------»»
bool ReceiveSQL::GetClientReadQueries(){
// check if we had any read transactions dealt to us
if(in_polls.at(0).revents & ZMQ_POLLIN){
++read_queries_recvd;
// We do. receive the next query
std::vector<zmq::message_t> outputs;
get_ok = Receive(clt_rtr_socket, outputs);
if(not get_ok){
Log(Concat("error receiving part ",outputs.size()+1," of Read query from client"),1);
++read_query_recv_fails;
return false;
}
// received message format should be a 4-part message
if(outputs.size()!=4){
Log(Concat("unexpected ",outputs.size()," part message in Read query from client"),1);
++read_query_recv_fails;
return false;
}
// The received message format should be the same format as for Write queries.
// 1. client ID
// 2. message ID
// 3. database name
// 4. SQL statement
// again the first two parts form a key used to track messages already handled.
std::string client_str="-"; uint32_t msg_int=-1; std::string dbname="-";
std::string qry_string="-";
if(outputs.size()>0){
client_str.resize(outputs.at(0).size(),'\0');
memcpy((void*)client_str.data(),outputs.at(0).data(),outputs.at(0).size());
}
if(outputs.size()>1) msg_int = *reinterpret_cast<uint32_t*>(outputs.at(1).data());
if(outputs.size()>2){
dbname.resize(outputs.at(2).size(),'\0');
memcpy((void*)dbname.data(),outputs.at(2).data(),outputs.at(2).size());
}
if(outputs.size()>3){
qry_string.resize(outputs.at(3).size(),'\0');
memcpy((void*)qry_string.data(),outputs.at(3).data(),outputs.at(3).size());
}
if(outputs.size()!=4){
Log(Concat("unexpected ",outputs.size()," part message in Write query from client"),1);
Log(Concat("client: '",client_str,"', msg_id: ",msg_int,", db: '",dbname,"'"),4);
++write_query_recv_fails;
return false;
}
std::pair<std::string, uint32_t> key{client_str,msg_int};
// check if we already know this query.
if(cache.count(key)){
// we've already run and sent the response to this query, resend it.
std::cout<<"we know this query: re-sending cached reply of:"<<std::endl;
//cache.at(key).Print();
resp_queue.emplace(key,cache.at(key));
cache.erase(key);
} else if(rd_txn_queue.count(key)==0 && resp_queue.count(key)==0){
Log("RECEIVED READ QUERY FROM CLIENT '"+client_str+"' with message id: "+std::to_string(msg_int),3);
// do a safety check to ensure this is actually a write query (optional)
//std::string query = reinterpret_cast<const char*>(outputs.at(3).data());
// std::string::find is case-sensitive, so cast to all uppercase
std::string uppercasequery;
for(int i=0; i<qry_string.length(); ++i) uppercasequery.append(1,std::toupper(qry_string[i]));
bool is_write_txn = (uppercasequery.find("INSERT")!=std::string::npos) ||
(uppercasequery.find("UPDATE")!=std::string::npos) ||
(uppercasequery.find("DELETE")!=std::string::npos) ||
(uppercasequery.find("INTO")!=std::string::npos);
if(not is_write_txn || (am_master && handle_unexpected_writes)){
// sanity check passed
Query msg{outputs.at(0), outputs.at(1), outputs.at(2), outputs.at(3)};
rd_txn_queue.emplace(key, msg);
} else {
// otherwise send a response saying this query should go via the PUB port
std::string err = "write transaction received by standby dealer socket";
Query msg{outputs.at(0), outputs.at(1), outputs.at(2), outputs.at(3), 0, err};
resp_queue.emplace(key, msg);
Log("Write transaction received on read transaction port",1);
return false;
}
} // else we've already got this message queued, ignore it.
} // else no read queries this time
/*
else {
std::cout<<"no read queries at input port"<<std::endl;
}
*/
return true;
}
// ««-------------- ≪ °◇◆◇° ≫ --------------»»
bool ReceiveSQL::GetClientLogMessages(){
// see if we had any write requests from clients
if(in_polls.at(3).revents & ZMQ_POLLIN){
Log("got a log message from client",4);
++log_msgs_recvd;
// we did. receive next message.
std::vector<zmq::message_t> outputs;
get_ok = Receive(log_sub_socket, outputs);
if(not get_ok){
Log(Concat("error receiving part ",outputs.size()+1," of Log message from client"),1);
++log_msg_recv_fails;
return false;
}
// received message format should be a 4-part message
if(outputs.size()!=4){
Log(Concat("unexpected ",outputs.size()," part message in Log msg from client"),1);
++log_msg_recv_fails;
return false;
}
// expected parts are:
// 1. identity of the sender client
// 2. a timestamp of when this occurred
// 3. a severity
// 4. the log message
// we do not send acks for log messages, so do not need to track them (no repeat sends)
std::string client_str="-"; std::string timestamp="-"; std::string log_str="-";
uint32_t severity;
if(outputs.size()>0){
client_str.resize(outputs.at(0).size(),'\0');
memcpy((void*)client_str.data(),outputs.at(0).data(),outputs.at(0).size());
}
if(outputs.size()>1){
timestamp.resize(outputs.at(2).size(),'\0');
memcpy((void*)timestamp.data(),outputs.at(2).data(),outputs.at(2).size());
}
if(outputs.size()>2) severity = *reinterpret_cast<uint32_t*>(outputs.at(2).data());
if(outputs.size()>3){
log_str.resize(outputs.at(3).size(),'\0');
memcpy((void*)log_str.data(),outputs.at(3).data(),outputs.at(3).size());
}
in_log_queue.emplace_back(client_str, timestamp, severity, log_str);
Log("Put client logmessage in queue: '"+log_str+"'",5);
} // else no log messages from clients
/*
else {
std::cout<<"no log messages at input port"<<std::endl;
}
*/
return true;
}
// ««-------------- ≪ °◇◆◇° ≫ --------------»»
bool ReceiveSQL::GetMiddlemanCheckin(){
// see if we had a presence broadcast from the other middleman
// as well as checking the master is still up, we also check whether both middlemen
// are in the same role, and if so initiate negotiatiation to promote/demote as necessary.
bool need_to_negotiate=false;
// if negotiations are started by the other middleman, we will propagate
// the received information to the Negotiation function
std::string their_header="";
std::string their_timestamp="";
// keep reading from the SUB socket until there are no more waiting messages.
// it's important we don't take any action until we've read out everything,
// to ensure we don't start negotiation based on old, stale requests.
while(in_polls.at(1).revents & ZMQ_POLLIN){
++mm_broadcasts_recvd; // FIXME this includes negotiation requests
// We do. Receive it.
std::vector<zmq::message_t> outputs;
get_ok = Receive(mm_rcv_socket, outputs);
if(not get_ok){
Log(Concat("error receiving message part ",outputs.size()+1," of message from middleman"),0);
++mm_broadcast_recv_fails; // FIXME this could include negotiation requests
return false;
}
// normal broadcast message is 1 part
if(outputs.size()==1){
// got a broadcast message format.
// the received message should be an integer indicating whether the other
// middleman is in the master role. If there's a clash, we'll need to negotiate.
uint32_t is_master = *(reinterpret_cast<uint32_t*>(outputs.at(0).data()));
if(is_master && am_master){
Log("Both middleman are masters! ...",3);
need_to_negotiate = true;
} else if(!is_master && !am_master){
Log("Neither middlemen are masters! ...",3);
// avoid unnecessary negotiation if we're fixed to being standby.
// it's possible both are fixed to being standby
// if not, the other standby will open negotiation eventually
if(not dont_promote) need_to_negotiate = true;
} else {
if(need_to_negotiate){
Log("...Disregarding stale role collision",3);
}
need_to_negotiate = false;
their_header="";
their_timestamp="";
}
last_mm_receipt = boost::posix_time::microsec_clock::universal_time();
} else if(outputs.size()==2){
// negotiation is done via the same socket, but involves 2-part messages.
// if the other middleman has invoked negotiation, we may have received 2 parts.
their_header = std::string(reinterpret_cast<const char*>(outputs.at(0).data()));
their_timestamp = std::string(reinterpret_cast<const char*>(outputs.at(1).data()));
if(their_header=="Negotiate"){
// it's a request to negotiate
need_to_negotiate = true;
} else if(their_header=="VerifyMaster" || their_header=="VerifyStandby"){
// These suggest negotiation completed.
if(need_to_negotiate){
Log("...Disregarding stale role collision",3);
}
need_to_negotiate = false;
their_header="";
their_timestamp="";
} else {
Log(Concat("Unrecognised message header: '",their_header,"' from middleman"),0);
// FIXME ignore it? would it be safer to negotiate, just to be sure?
}
} else {
// else more than 2 parts
Log(Concat("unexpected ",outputs.size()," part message from middleman"),0);
++mm_broadcast_recv_fails; // FIXME this could include negotiation requests
return false;
}