-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdmq.c
2250 lines (1940 loc) · 59.9 KB
/
dmq.c
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
/*----------------------------------------------------------------------------
*
* dmq.c
* Distributed message queue.
*
*
* Backend to remote backend messaging with memqueue-like interface.
* COPY protocol is used as a transport to avoid unnecessary overhead of sql
* parsing.
* Sender is a custom bgworker that starts with postgres, can open multiple
* remote connections and keeps open memory queue with each ordinary backend.
* It's a sender responsibility to establish a connection with a remote
* counterpart. Sender can send heartbeats to allow early detection of dead
* connections. Also it can stubbornly try to reestablish dead connection.
* Receiver is an ordinary backend spawned by a postmaster upon sender
* connection request. As it first call sender will call dmq_receiver_loop()
* function that will switch fe/be protocol to a COPY mode and enters endless
* receiving loop.
*
* XXX: needs better PQerror reporting logic -- perhaps once per given Idle
* connection.
*
* XXX: is there max size for a connstr?
*
* Copyright (c) 2019-2021, Postgres Professional
*
*----------------------------------------------------------------------------
*/
#include "postgres.h"
#include "dmq.h"
#include "logger.h"
#include "compat.h"
#include "mtm_utils.h"
#include "multimaster.h"
#include "state.h"
#include "access/transam.h"
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "executor/executor.h"
#include "utils/builtins.h"
#include "utils/timestamp.h"
#include "storage/shm_toc.h"
#include "postmaster/autovacuum.h"
#include "postmaster/interrupt.h"
#include "replication/walsender.h"
#include "storage/shm_mq.h"
#include "storage/ipc.h"
#include "tcop/tcopprot.h"
#include "utils/dynahash.h"
#include "utils/ps_status.h"
#define DMQ_MQ_SIZE ((Size) 65536)
#define DMQ_MQ_MAGIC 0x646d71
/*
* Shared data structures to hold current connections topology.
* All that stuff can be moved to persistent tables to avoid hardcoded
* size limits, but now it doesn't seems to be worth of troubles.
*/
#define DMQ_CONNSTR_MAX_LEN 150
#define DMQ_MAX_SUBS_PER_BACKEND 10
#define DMQ_MAX_DESTINATIONS 10
#define DMQ_MAX_RECEIVERS 10
typedef enum
{
Idle, /* upon init or failure */
Connecting, /* upon PQconnectStart */
Negotiating, /* upon PQconnectPoll == OK */
Active, /* upon dmq_receiver_loop() response */
} DmqConnState;
typedef struct
{
bool active;
char sender_name[DMQ_NAME_MAXLEN];
char receiver_name[DMQ_NAME_MAXLEN];
char connstr[DMQ_CONNSTR_MAX_LEN];
int recv_timeout;
PGconn *pgconn;
DmqConnState state;
double conn_start_time;
int pos;
int8 mask_pos;
bool reconnect_requested;
} DmqDestination;
typedef struct
{
char stream_name[DMQ_STREAM_NAME_MAXLEN];
int procno;
uint64 procno_gen;
} DmqStreamSubscription;
/* receiver publishes this in shmem to let subscriber find his shm_mq */
typedef struct
{
dsm_handle h;
uint64 procno_gen;
} ReceiverDSMHandle;
/* receiver state in shmem */
typedef struct
{
char name[DMQ_NAME_MAXLEN];
pid_t pid;
ReceiverDSMHandle *dsm_handles; /* indexed by pgprocno */
} DmqReceiverSlot;
/* Global state for dmq */
struct DmqSharedState
{
LWLock *lock;
/* sender stuff */
pid_t sender_pid;
dsm_handle out_dsm;
DmqDestination destinations[DMQ_MAX_DESTINATIONS];
/*
* Stores counters incremented on each reconnect to destination, indexed
* by receiver mask_pos. This allows to detect conn failures to avoid
* infinite waiting for response when request could have been dropped,
* c.f. dmq_fill_sconn_cnt and dmq_purge_failed_participants.
*
* XXX This mechanism is unreliable and ugly.
* Unreliable, because though it saves from infinite waiting for reply, it
* doesn't save from potential deadlocks. Deadlocks may arise whenever a
* loop of nodes makes request-response sequences because request A->B and
* A's response to B's request go via the same TCP channel; thus, if all
* queues of loop in one direction are filled with requests, nobody will
* be able to answer.
*
* We could control the situation by ensuring 1) all possible requests
* node sends at time could fit in the output buffers 2) node never
* repeats the request until the previous one is delivered or dropped.
* However, to honor the 2), we must terminate send connection whenever
* receive conn failed (and thus we gonna to retry the requests) to flush
* previous possible undelivered requests, which we don't do currently.
*
* Ultimate non-deadlockable solution without such hacks would be to
* divide the job between different channels: A sends its requests to B
* and receives responses from it via one TCP channel, and B sends its
* requests to A and receives responses via another one. Probably this is
* not worthwhile though as it would make dmq more complicated and
* increase number of shm_mqs.
*
* Besides, the counters are ugly because they require the external code
* to remember sender counters before request and check them while
* waiting for reply; moreover, this checking must be based on timeouts
* as nobody would wake the clients on send conn failures.
*
* No locks are used because we don't care much about correct/up-to-date
* reads, though well aligned ints are atomic anyway.
*/
volatile int sconn_cnt[DMQ_MAX_DESTINATIONS];
/*
* Receivers stuff. Some notes on shm_mq management: one of the subtle
* requirements here is avoid losing the message with live receiver, or we
* might fool the counterparty to wait for an answer while request has
* been dropped. OTOH, if receiver conn is dead, there is no point in
* waiting for messages as we obviously never know when they arrive. Hence
* naturally follows that mq should be created by receiver, not subscriber
* -- i.e. attached queue at subscriber side must mean receiver appeared
* (so we can wait for messages), and if he dies, he will detach from the
* queue so we'll get an error in shm_mq_receive.
*
* shm_mq doesn't allow reattachment to the queue, and even if it did, it
* would be cumbersome to maintain the failure detection logic as outlined
* above (see dmq_pop_nb for user-facing semantics). So each
* receiver-subscriber pair uses separate shm_mq (and underlying dsm
* segment). To distinguish between different processes with the same
* pgprocno, procno generations were invented. As additional nicety, this
* means subscriber can never get messages aimed to another backend (with
* the same procno). Also mqs are created on demand, backend who never
* subscribes doesn't waste memory on queue (though currently this is of
* little help as mqs for dead backends are not cleaned up until they are
* reused).
*/
/*
* using separate cv per receiver would be perceptibly more complicated
* and negligibly more performant
*/
ConditionVariable shm_mq_creation_cv;
/*
* Indexed by pgprocno; each subscriber increments himself here so we
* could distinguish different processes with the same pgprocno.
*/
uint64 *procno_gens;
DmqReceiverSlot receivers[DMQ_MAX_RECEIVERS];
} *dmq_state;
/* special value for sconn_cnt[] meaning the connection is dead */
#define DMQSCONN_DEAD 0
static HTAB *dmq_subscriptions;
/* Backend-local i/o queues. */
struct
{
/* to send */
shm_mq_handle *mq_outh;
/* to receive */
char curr_stream_name[DMQ_STREAM_NAME_MAXLEN];
uint64 my_procno_gen;
int n_inhandles;
struct
{
dsm_segment *dsm_seg;
shm_mq_handle *mqh;
char name[DMQ_NAME_MAXLEN];
int8 mask_pos;
} inhandles[DMQ_MAX_RECEIVERS];
} dmq_local;
/* hack: copy definition to get inside with our dirty hands */
typedef struct
{
slock_t mq_mutex;
PGPROC *mq_receiver;
PGPROC *mq_sender;
pg_atomic_uint64 mq_bytes_read;
pg_atomic_uint64 mq_bytes_written;
Size mq_ring_size;
bool mq_detached;
uint8 mq_ring_offset;
char mq_ring[FLEXIBLE_ARRAY_MEMBER];
} my_shm_mq;
/* Flags set by signal handlers */
static volatile sig_atomic_t got_SIGHUP = false;
static shmem_startup_hook_type PreviousShmemStartupHook;
void *(*dmq_receiver_start_hook)(char *sender_name);
dmq_hook_type dmq_receiver_stop_hook;
dmq_hook_type dmq_sender_connect_hook;
dmq_hook_type dmq_sender_disconnect_hook;
void (*dmq_sender_heartbeat_hook)(char *receiver_name, StringInfo buf) = NULL;
void (*dmq_receiver_heartbeat_hook)(char *sender_name, StringInfo msg, void *extra) = NULL;
void dmq_sender_main(Datum main_arg);
PG_FUNCTION_INFO_V1(dmq_receiver_loop);
/*****************************************************************************
*
* Helpers
*
*****************************************************************************/
static double
dmq_now(void)
{
instr_time cur_time;
INSTR_TIME_SET_CURRENT(cur_time);
return INSTR_TIME_GET_MILLISEC(cur_time);
}
/*****************************************************************************
*
* Initialization
*
*****************************************************************************/
/* SIGHUP: set flag to reload configuration at next convenient time */
static void
dmq_sighup_handler(SIGNAL_ARGS)
{
int save_errno = errno;
got_SIGHUP = true;
/* Waken anything waiting on the process latch */
SetLatch(MyLatch);
errno = save_errno;
}
/* per one receiver slot */
static Size
receiver_dsm_handles_size(void)
{
return mul_size(sizeof(ReceiverDSMHandle), MaxBackends);
}
/*
* Set pointer to dmq shared state in all backends.
*/
static void
dmq_shmem_startup_hook(void)
{
bool found;
HASHCTL hash_info;
if (PreviousShmemStartupHook)
PreviousShmemStartupHook();
MemSet(&hash_info, 0, sizeof(hash_info));
hash_info.keysize = DMQ_NAME_MAXLEN;
hash_info.entrysize = sizeof(DmqStreamSubscription);
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
dmq_state = ShmemInitStruct("dmq",
sizeof(struct DmqSharedState),
&found);
if (!found)
{
int i;
bool procno_gens_found;
dmq_state->lock = &(GetNamedLWLockTranche("dmq"))->lock;
dmq_state->out_dsm = DSM_HANDLE_INVALID;
memset(dmq_state->destinations, '\0', sizeof(DmqDestination) * DMQ_MAX_DESTINATIONS);
dmq_state->sender_pid = 0;
ConditionVariableInit(&dmq_state->shm_mq_creation_cv);
dmq_state->procno_gens =
ShmemInitStruct("dmq-procnogens",
mul_size(sizeof(uint64), MaxBackends),
&procno_gens_found);
Assert(!procno_gens_found);
MemSet(dmq_state->procno_gens, '\0', sizeof(uint64) * MaxBackends);
for (i = 0; i < DMQ_MAX_RECEIVERS; i++)
{
bool dsm_handles_found;
char dsm_handles_shmem_name[32];
dmq_state->receivers[i].name[0] = '\0';
dmq_state->receivers[i].pid = 0;
snprintf(dsm_handles_shmem_name, 32, "dmq-%d", i);
dmq_state->receivers[i].dsm_handles =
ShmemInitStruct(dsm_handles_shmem_name,
receiver_dsm_handles_size(),
&dsm_handles_found);
Assert(!dsm_handles_found);
MemSet(dmq_state->receivers[i].dsm_handles, '\0',
receiver_dsm_handles_size());
}
}
dmq_subscriptions = ShmemInitHash("dmq_stream_subscriptions",
DMQ_MAX_SUBS_PER_BACKEND * MaxBackends,
DMQ_MAX_SUBS_PER_BACKEND * MaxBackends,
&hash_info,
HASH_ELEM);
LWLockRelease(AddinShmemInitLock);
}
static Size
dmq_shmem_size(void)
{
Size size = 0;
int maxbackends = 0;
maxbackends = MaxConnections + autovacuum_max_workers +
max_worker_processes + max_wal_senders + 1;
size = add_size(size, sizeof(struct DmqSharedState));
size = add_size(size, hash_estimate_size(DMQ_MAX_SUBS_PER_BACKEND * maxbackends,
sizeof(DmqStreamSubscription)));
return MAXALIGN(size);
}
void
dmq_init(int send_timeout, int connect_timeout)
{
BackgroundWorker worker;
if (!process_shared_preload_libraries_in_progress)
return;
/* Reserve area for our shared state */
RequestAddinShmemSpace(dmq_shmem_size());
RequestNamedLWLockTranche("dmq", 1);
/* Set up common data for all our workers */
memset(&worker, 0, sizeof(worker));
worker.bgw_flags = BGWORKER_SHMEM_ACCESS;
worker.bgw_start_time = BgWorkerStart_ConsistentState;
worker.bgw_restart_time = 5;
worker.bgw_notify_pid = 0;
memcpy(worker.bgw_extra, &send_timeout, sizeof(int));
memcpy(worker.bgw_extra + sizeof(int), &connect_timeout, sizeof(int));
sprintf(worker.bgw_library_name, "multimaster");
sprintf(worker.bgw_function_name, "dmq_sender_main");
snprintf(worker.bgw_name, BGW_MAXLEN, "mtm-dmq-sender");
snprintf(worker.bgw_type, BGW_MAXLEN, "mtm-dmq-sender");
RegisterBackgroundWorker(&worker);
/* Register shmem hooks */
PreviousShmemStartupHook = shmem_startup_hook;
shmem_startup_hook = dmq_shmem_startup_hook;
}
static Size
dmq_toc_size()
{
int i;
shm_toc_estimator e;
shm_toc_initialize_estimator(&e);
for (i = 0; i < MaxBackends; i++)
shm_toc_estimate_chunk(&e, DMQ_MQ_SIZE);
shm_toc_estimate_keys(&e, MaxBackends);
return shm_toc_estimate(&e);
}
/*****************************************************************************
*
* Sender
*
*****************************************************************************/
static int
fe_send(PGconn *conn, char *msg, size_t len)
{
if (PQputCopyData(conn, msg, len) < 0)
return -1;
/* XXX: move PQflush out of the loop? */
if (PQflush(conn) < 0)
return -1;
/*
* libpq's PQflush() in pg 12 swallows socket errors during write, so we
* need to try to read from socket to detect broken connections.
*/
if (!PQconsumeInput(conn))
return -1;
return 0;
}
static void
dmq_send(DmqDestination *conns, int conn_id, char *data, size_t len)
{
int ret = fe_send(conns[conn_id].pgconn, data, len);
if (ret < 0)
{
conns[conn_id].state = Idle;
dmq_state->sconn_cnt[conns[conn_id].mask_pos] = DMQSCONN_DEAD;
mtm_log(DmqStateFinal,
"[DMQ] failed to send message to %s: %s",
conns[conn_id].receiver_name,
PQerrorMessage(conns[conn_id].pgconn));
dmq_sender_disconnect_hook(conns[conn_id].receiver_name);
}
else if (data[0] != 'H') /* skip logging heartbeats */
{
mtm_log(DmqTraceOutgoing,
"[DMQ] sent message (l=%zu, m=%s) to %s",
len, (char *) data, conns[conn_id].receiver_name);
}
}
static void
dmq_sender_at_exit(int status, Datum arg)
{
int i;
LWLockAcquire(dmq_state->lock, LW_SHARED);
for (i = 0; i < DMQ_MAX_RECEIVERS; i++)
{
if (dmq_state->receivers[i].name[0] != '\0' &&
dmq_state->receivers[i].pid > 0)
{
kill(dmq_state->receivers[i].pid, SIGTERM);
}
}
LWLockRelease(dmq_state->lock);
/*
* Restart the Campaigner to be sure that all critical data reset before the
* next voting.
*/
CampaignerStop();
}
void
dmq_sender_main(Datum main_arg)
{
int i;
dsm_segment *seg;
shm_toc *toc;
shm_mq_handle **mq_handles;
WaitEventSet *set;
DmqDestination conns[DMQ_MAX_DESTINATIONS];
int heartbeat_send_timeout;
int connect_timeout;
StringInfoData heartbeat_buf; /* heartbeat data is accumulated here */
/*
* Seconds dmq_state->sconn_cnt to save the counter value when
* conn is dead.
*/
int sconn_cnt[DMQ_MAX_DESTINATIONS];
double prev_timer_at = dmq_now();
MtmBackgroundWorker = true; /* includes bgw name in mtm_log */
on_shmem_exit(dmq_sender_at_exit, (Datum) 0);
initStringInfo(&heartbeat_buf);
/* init this worker */
pqsignal(SIGHUP, dmq_sighup_handler);
pqsignal(SIGTERM, die);
BackgroundWorkerUnblockSignals();
MtmDisableTimeouts();
memcpy(&heartbeat_send_timeout, MyBgworkerEntry->bgw_extra, sizeof(int));
memcpy(&connect_timeout, MyBgworkerEntry->bgw_extra + sizeof(int), sizeof(int));
/* setup queue receivers */
seg = dsm_create(dmq_toc_size(), 0);
dsm_pin_segment(seg);
toc = shm_toc_create(DMQ_MQ_MAGIC, dsm_segment_address(seg),
dmq_toc_size());
mq_handles = palloc(MaxBackends * sizeof(shm_mq_handle *));
for (i = 0; i < MaxBackends; i++)
{
shm_mq *mq;
mq = shm_mq_create(shm_toc_allocate(toc, DMQ_MQ_SIZE), DMQ_MQ_SIZE);
shm_toc_insert(toc, i, mq);
shm_mq_set_receiver(mq, MyProc);
mq_handles[i] = shm_mq_attach(mq, seg, NULL);
}
for (i = 0; i < DMQ_MAX_DESTINATIONS; i++)
{
conns[i].active = false;
}
LWLockAcquire(dmq_state->lock, LW_EXCLUSIVE);
dmq_state->sender_pid = MyProcPid;
dmq_state->out_dsm = dsm_segment_handle(seg);
LWLockRelease(dmq_state->lock);
set = CreateWaitEventSet(CurrentMemoryContext, 15);
AddWaitEventToSet(set, WL_POSTMASTER_DEATH, PGINVALID_SOCKET, NULL, NULL);
AddWaitEventToSet(set, WL_LATCH_SET, PGINVALID_SOCKET, MyLatch, NULL);
got_SIGHUP = true;
for (;;)
{
WaitEvent event;
int nevents;
bool wait = true;
double now_millisec;
bool timer_event = false;
if (ProcDiePending)
break;
/*
* Read new connections from shared memory.
*/
if (got_SIGHUP)
{
got_SIGHUP = false;
LWLockAcquire(dmq_state->lock, LW_SHARED);
for (i = 0; i < DMQ_MAX_DESTINATIONS; i++)
{
DmqDestination *dest = &(dmq_state->destinations[i]);
/* start connection for a freshly added destination */
if (dest->active && !conns[i].active)
{
conns[i] = *dest;
Assert(conns[i].pgconn == NULL);
conns[i].state = Idle;
sconn_cnt[dest->mask_pos] = 0;
dmq_state->sconn_cnt[dest->mask_pos] = DMQSCONN_DEAD;
prev_timer_at = 0; /* do not wait for timer event */
}
/* close connection to deleted destination */
else if (!dest->active && conns[i].active)
{
PQfinish(conns[i].pgconn);
conns[i].active = false;
conns[i].pgconn = NULL;
}
else if (dest->active && conns[i].active &&
dest->reconnect_requested)
{
dest->reconnect_requested = false;
PQfinish(conns[i].pgconn);
conns[i].pgconn = NULL;
if (conns[i].state == Active)
{
dmq_sender_disconnect_hook(conns[i].receiver_name);
}
conns[i].state = Idle;
dmq_state->sconn_cnt[dest->mask_pos] = DMQSCONN_DEAD;
}
}
LWLockRelease(dmq_state->lock);
}
/*
* Transfer data from backend queues to their remote counterparts.
*/
for (i = 0; i < MaxBackends; i++)
{
void *data;
Size len;
shm_mq_result res;
res = shm_mq_receive(mq_handles[i], &len, &data, true);
if (res == SHM_MQ_SUCCESS)
{
int conn_id;
/* first byte is connection_id */
conn_id = *(char *) data;
data = (char *) data + 1;
len -= 1;
Assert(0 <= conn_id && conn_id < DMQ_MAX_DESTINATIONS);
if (conns[conn_id].state == Active)
{
dmq_send(conns, conn_id, data, len);
}
else
{
mtm_log(WARNING,
"[DMQ] dropping message (l=%zu, m=%s) to disconnected %s",
len, (char *) data, conns[conn_id].receiver_name);
}
wait = false;
}
else if (res == SHM_MQ_DETACHED)
{
shm_mq *mq = shm_mq_get_queue(mq_handles[i]);
/*
* Overwrite old mq struct since mq api don't have a way to
* reattach detached queue.
*/
shm_mq_detach(mq_handles[i]);
mq = shm_mq_create(mq, DMQ_MQ_SIZE);
shm_mq_set_receiver(mq, MyProc);
mq_handles[i] = shm_mq_attach(mq, seg, NULL);
mtm_log(DmqTraceShmMq,
"[DMQ] sender reattached shm_mq to procno %d", i);
}
}
/*
* Generate timeout or socket events.
*
*
* XXX: here we expect that whole cycle takes less then 250-100 ms.
* Otherwise we can stuck with timer_event forever.
*/
now_millisec = dmq_now();
if (now_millisec - prev_timer_at > heartbeat_send_timeout)
{
prev_timer_at = now_millisec;
timer_event = true;
}
else
{
nevents = WaitEventSetWait(set, wait ? 100 : 0, &event,
1, PG_WAIT_EXTENSION);
}
/*
* Handle timer event: reconnect previously broken connection or send
* heartbeats.
*/
if (timer_event)
{
uintptr_t conn_id;
for (conn_id = 0; conn_id < DMQ_MAX_DESTINATIONS; conn_id++)
{
if (!conns[conn_id].active)
continue;
/* Idle --> Connecting */
if (conns[conn_id].state == Idle)
{
double pqtime;
if (conns[conn_id].pgconn)
PQfinish(conns[conn_id].pgconn);
pqtime = dmq_now();
mtm_log(DmqStateIntermediate, "[DMQ] PQconnectStart to %s", conns[conn_id].connstr);
conns[conn_id].pgconn = PQconnectStart(conns[conn_id].connstr);
mtm_log(DmqPqTiming, "[DMQ] [TIMING] pqs = %f ms", dmq_now() - pqtime);
if (PQstatus(conns[conn_id].pgconn) == CONNECTION_BAD)
{
conns[conn_id].state = Idle;
mtm_log(DmqStateFinal,
"[DMQ] failed to start connection with %s (%s): %s",
conns[conn_id].receiver_name,
conns[conn_id].connstr,
PQerrorMessage(conns[conn_id].pgconn));
}
else
{
conns[conn_id].conn_start_time = dmq_now();
conns[conn_id].state = Connecting;
conns[conn_id].pos = AddWaitEventToSet(set, WL_SOCKET_CONNECTED,
PQsocket(conns[conn_id].pgconn),
NULL, (void *) conn_id);
mtm_log(DmqStateIntermediate,
"[DMQ] switching %s from Idle to Connecting on '%s'",
conns[conn_id].receiver_name,
conns[conn_id].connstr);
}
}
/* Heartbeat */
else if (conns[conn_id].state == Active)
{
resetStringInfo(&heartbeat_buf);
/* stream name is cstring by convention */
appendStringInfoChar(&heartbeat_buf, 'H');
appendStringInfoChar(&heartbeat_buf, '\0');
/* Allow user to stuff some payload into the heartbeat */
if (dmq_sender_heartbeat_hook != NULL)
dmq_sender_heartbeat_hook(conns[conn_id].receiver_name,
&heartbeat_buf);
dmq_send(conns, conn_id, heartbeat_buf.data, heartbeat_buf.len);
}
/*
* Do we need to abort connection attempt due to timeout?
*/
else if (conns[conn_id].state == Connecting &&
connect_timeout > 0 &&
dmq_now() - conns[conn_id].conn_start_time >= connect_timeout * 1000)
{
conns[conn_id].state = Idle;
DeleteWaitEvent(set, conns[conn_id].pos);
mtm_log(DmqStateFinal,
"[DMQ] timed out establishing connection with %s (%s)",
conns[conn_id].receiver_name,
conns[conn_id].connstr);
}
}
}
/*
* Handle all the connection machinery: consequently go through
* Connecting --> Negotiating --> Active states.
*/
else if (nevents > 0 && event.events & WL_SOCKET_MASK)
{
uintptr_t conn_id = (uintptr_t) event.user_data;
Assert(conns[conn_id].active);
switch (conns[conn_id].state)
{
case Idle:
Assert(false);
break;
/*
* Await for connection establishment and call
* dmq_receiver_loop()
*/
case Connecting:
{
double pqtime;
PostgresPollingStatusType status;
int pos = event.pos;
pqtime = dmq_now();
status = MtmPQconnectPoll(conns[conn_id].pgconn);
mtm_log(DmqPqTiming, "[DMQ] [TIMING] pqp = %f ms", dmq_now() - pqtime);
mtm_log(DmqStateIntermediate,
"[DMQ] Connecting: PostgresPollingStatusType = %d on %s",
status,
conns[conn_id].receiver_name);
/*
* PQconnectPoll() can recreate socket behind the
* scene, so re-register it in WaitEventSet.
*/
if (status == PGRES_POLLING_READING || status == PGRES_POLLING_WRITING)
{
DeleteWaitEvent(set, pos);
pos = AddWaitEventToSet(set, WL_SOCKET_CONNECTED,
PQsocket(conns[conn_id].pgconn),
NULL, (void *) conn_id);
conns[conn_id].pos = pos;
}
if (status == PGRES_POLLING_READING)
{
ModifyWaitEvent(set, pos, WL_SOCKET_READABLE, NULL);
mtm_log(DmqStateIntermediate,
"[DMQ] Connecting: modify wait event to WL_SOCKET_READABLE on %s",
conns[conn_id].receiver_name);
}
else if (status == PGRES_POLLING_WRITING)
{
ModifyWaitEvent(set, pos, WL_SOCKET_WRITEABLE, NULL);
mtm_log(DmqStateIntermediate,
"[DMQ] Connecting: modify wait event to WL_SOCKET_WRITEABLE on %s",
conns[conn_id].receiver_name);
}
else if (status == PGRES_POLLING_OK)
{
char *sender_name = conns[conn_id].sender_name;
char *query = psprintf("select mtm.dmq_receiver_loop('%s', %d)",
sender_name, conns[conn_id].recv_timeout);
conns[conn_id].state = Negotiating;
ModifyWaitEvent(set, pos, WL_SOCKET_READABLE, NULL);
PQsendQuery(conns[conn_id].pgconn, query);
mtm_log(DmqStateIntermediate,
"[DMQ] switching %s from Connecting to Negotiating",
conns[conn_id].receiver_name);
}
else if (status == PGRES_POLLING_FAILED)
{
conns[conn_id].state = Idle;
DeleteWaitEvent(set, pos);
mtm_log(DmqStateIntermediate,
"[DMQ] failed to connect with %s (%s): %s",
conns[conn_id].receiver_name,
conns[conn_id].connstr,
PQerrorMessage(conns[conn_id].pgconn));
}
else
Assert(false);
break;
}
/*
* Await for response to dmq_receiver_loop() call and
* switch to active state.
*/
case Negotiating:
Assert(event.events & WL_SOCKET_READABLE);
if (!PQconsumeInput(conns[conn_id].pgconn))
{
conns[conn_id].state = Idle;
DeleteWaitEvent(set, event.pos);
mtm_log(DmqStateIntermediate,
"[DMQ] failed to get handshake from %s: %s",
conns[conn_id].receiver_name,
PQerrorMessage(conns[i].pgconn));
}
if (!PQisBusy(conns[conn_id].pgconn))
{
int8 mask_pos = conns[conn_id].mask_pos;
/*
* XXX check here that dmq_receiver_loop not failed?
*/
conns[conn_id].state = Active;
DeleteWaitEvent(set, event.pos);
PQsetnonblocking(conns[conn_id].pgconn, 1);
sconn_cnt[mask_pos]++;
dmq_state->sconn_cnt[mask_pos] = sconn_cnt[mask_pos];
mtm_log(DmqStateFinal,
"[DMQ] connected to %s",
conns[conn_id].receiver_name);
dmq_sender_connect_hook(conns[conn_id].receiver_name);
}
break;
/* Do nothing and check that connection is still alive */
case Active:
Assert(event.events & WL_SOCKET_READABLE);
if (!PQconsumeInput(conns[conn_id].pgconn))
{
conns[conn_id].state = Idle;
dmq_state->sconn_cnt[conns[conn_id].mask_pos] = DMQSCONN_DEAD;
mtm_log(DmqStateFinal,
"[DMQ] connection error with %s: %s",
conns[conn_id].receiver_name,
PQerrorMessage(conns[conn_id].pgconn));
dmq_sender_disconnect_hook(conns[conn_id].receiver_name);
}
break;
}
}
else if (nevents > 0 && event.events & WL_LATCH_SET)
{
ResetLatch(MyLatch);
}
else if (nevents > 0 && event.events & WL_POSTMASTER_DEATH)
{
proc_exit(1);
}
CHECK_FOR_INTERRUPTS();
}
FreeWaitEventSet(set);
}
/*****************************************************************************
*
* Receiver stuff
*
*****************************************************************************/
/*
* Get shm_mq ring buffer available space.
*
* We use this in dmq receiver in case when we need to bu sure that next
* message will definitely fit into buffer and won't block sender.
*/
static Size
shm_mq_available(shm_mq_handle *mqh)
{
uint64 rb;
uint64 wb;
uint64 used;
my_shm_mq *mq = (void *) shm_mq_get_queue(mqh);
/* Compute number of ring buffer bytes used and available. */
rb = pg_atomic_read_u64(&mq->mq_bytes_read);
wb = pg_atomic_read_u64(&mq->mq_bytes_written);
used = wb - rb;
Assert(wb >= rb);
Assert(used <= mq->mq_ring_size);
return mq->mq_ring_size - used;
}
/* recreate shm_mq to the given subscriber */
static void
dmq_receiver_recreate_mq(DmqReceiverSlot *my_slot,
int procno, uint64 procno_gen,
dsm_segment **seg_p, shm_mq_handle **mq_handle_p,
bool locked)
{
shm_mq *mq;
/* release previous dsm, if any */
/* shm_mq_detach is done automatically on dsm detach */
if (*seg_p != NULL)
dsm_detach(*seg_p);
*seg_p = NULL;
*mq_handle_p = NULL;
/* allocate a new one, put shm_mq there */
*seg_p = dsm_create(DMQ_MQ_SIZE, 0);
dsm_pin_mapping(*seg_p);
mq = shm_mq_create(dsm_segment_address(*seg_p), DMQ_MQ_SIZE);
shm_mq_set_sender(mq, MyProc);
*mq_handle_p = shm_mq_attach(mq, *seg_p, NULL);
/* and publish it */
if (!locked)
LWLockAcquire(dmq_state->lock, LW_EXCLUSIVE);
my_slot->dsm_handles[procno].h = dsm_segment_handle(*seg_p);
my_slot->dsm_handles[procno].procno_gen = procno_gen;
if (!locked)
LWLockRelease(dmq_state->lock);
mtm_log(DmqTraceShmMq, "[DMQ] created shm_mq to proc <%d, " UINT64_FORMAT ">, dsm handle %u",
procno, procno_gen, dsm_segment_handle(*seg_p));