forked from pgEdge/spock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spock_failover_slots.c
1487 lines (1270 loc) · 40.2 KB
/
spock_failover_slots.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
/*-------------------------------------------------------------------------
*
* spock_failover_slot.c
* Postgres Failover Slots
*
* Copyright (c) 2022-2023, pgEdge, Inc.
* Portions Copyright (c) 2023, EnterpriseDB Corporation.
* Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, The Regents of the University of California
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <dirent.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>
#include "funcapi.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "access/genam.h"
#if PG_VERSION_NUM >= 120000
#include "access/table.h"
#else
#include "access/heapam.h"
#define table_open heap_open
#define table_close heap_close
#endif
#include "access/xact.h"
#if PG_VERSION_NUM >= 150000
#include "access/xlogrecovery.h"
#endif
#include "catalog/indexing.h"
#include "catalog/pg_database.h"
#include "postmaster/bgworker.h"
#if PG_VERSION_NUM >= 130000
#include "postmaster/interrupt.h"
#endif
#include "replication/decode.h"
#include "replication/logical.h"
#include "replication/slot.h"
#include "replication/walreceiver.h"
#include "replication/walsender.h"
#include "storage/ipc.h"
#include "storage/procarray.h"
#include "tcop/tcopprot.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/fmgrprotos.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/pg_lsn.h"
#include "utils/resowner.h"
#include "utils/snapmgr.h"
#include "utils/varlena.h"
#include "libpq-fe.h"
#include "libpq/auth.h"
#include "libpq/libpq.h"
#if PG_VERSION_NUM < 130000
#define SignalHandlerForConfigReload PostgresSigHupHandler
#define GetWalRcvFlushRecPtr GetWalRcvWriteRecPtr
#endif
#define WORKER_NAP_TIME 60000L
#define WORKER_WAIT_FEEDBACK 10000L
typedef struct RemoteSlot
{
char *name;
char *plugin;
char *database;
bool two_phase;
XLogRecPtr restart_lsn;
XLogRecPtr confirmed_lsn;
TransactionId catalog_xmin;
} RemoteSlot;
typedef enum FailoverSlotFilterKey
{
FAILOVERSLOT_FILTER_NAME = 1,
FAILOVERSLOT_FILTER_NAME_LIKE,
FAILOVERSLOT_FILTER_PLUGIN
} FailoverSlotFilterKey;
typedef struct FailoverSlotFilter
{
FailoverSlotFilterKey key;
char *val; /* eg: test_decoding */
} FailoverSlotFilter;
/* Used for physical-before-logical ordering */
static char *standby_slot_names_raw;
static char *standby_slot_names_string = NULL;
List *standby_slot_names = NIL;
int standby_slots_min_confirmed;
XLogRecPtr standby_slot_names_oldest_flush_lsn = InvalidXLogRecPtr;
/* Slots to sync */
char *spock_failover_slots_dsn;
char *spock_failover_slot_names;
static char *spock_failover_slot_names_str = NULL;
static List *spock_failover_slot_names_list = NIL;
static bool spock_failover_slots_drop = true;
char *spock_failover_slots_version_str;
void spock_init_failover_slot(void);
PGDLLEXPORT void spock_failover_slots_main(Datum main_arg);
static bool
check_failover_slot_names(char **newval, void **extra, GucSource source)
{
List *namelist = NIL;
char *rawname = pstrdup(*newval);
bool valid;
valid = SplitIdentifierString(rawname, ',', &namelist);
if (!valid)
GUC_check_errdetail("List syntax is invalid.");
pfree(rawname);
list_free(namelist);
return valid;
}
static void
assign_failover_slot_names(const char *newval, void *extra)
{
MemoryContext old_ctx;
List *slot_names_list = NIL;
ListCell *lc;
/* cleanup memory to prevent leaking or SET/config reload */
if (spock_failover_slot_names_str)
pfree(spock_failover_slot_names_str);
if (spock_failover_slot_names_list)
{
foreach (lc, spock_failover_slot_names_list)
{
FailoverSlotFilter *filter = lfirst(lc);
/* val was pointer to spock_failover_slot_names_str */
pfree(filter);
}
list_free(spock_failover_slot_names_list);
}
spock_failover_slot_names_list = NIL;
/* Allocate memory in long lasting context. */
old_ctx = MemoryContextSwitchTo(TopMemoryContext);
spock_failover_slot_names_str = pstrdup(newval);
SplitIdentifierString(spock_failover_slot_names_str, ',', &slot_names_list);
foreach (lc, slot_names_list)
{
char *raw_val = lfirst(lc);
char *key = strtok(raw_val, ":");
FailoverSlotFilter *filter = palloc(sizeof(FailoverSlotFilter));
filter->val = strtok(NULL, ":");
/* Default key is name */
if (!filter->val)
{
filter->val = key;
filter->key = FAILOVERSLOT_FILTER_NAME;
}
else if (strcmp(key, "name") == 0)
filter->key = FAILOVERSLOT_FILTER_NAME;
else if (strcmp(key, "name_like") == 0)
filter->key = FAILOVERSLOT_FILTER_NAME_LIKE;
else if (strcmp(key, "plugin") == 0)
filter->key = FAILOVERSLOT_FILTER_PLUGIN;
else
ereport(
ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg(
"unrecognized synchronize_failover_slot_names key \"%s\"",
key)));
/* Check that there was just one ':' */
if (strtok(NULL, ":"))
ereport(
ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg(
"unrecognized synchronize_failover_slot_names format")));
spock_failover_slot_names_list =
lappend(spock_failover_slot_names_list, filter);
}
/* Clean the temporary list, but not the contents. */
list_free(slot_names_list);
MemoryContextSwitchTo(old_ctx);
}
static bool
check_standby_slot_names(char **newval, void **extra, GucSource source)
{
List *namelist = NIL;
char *rawname = pstrdup(*newval);
bool valid;
valid = SplitIdentifierString(rawname, ',', &namelist);
if (!valid)
GUC_check_errdetail("List syntax is invalid.");
pfree(rawname);
list_free(namelist);
return valid;
}
static void
assign_standby_slot_names(const char *newval, void *extra)
{
MemoryContext old_ctx;
if (standby_slot_names_string)
pfree(standby_slot_names_string);
if (standby_slot_names)
list_free(standby_slot_names);
/*
* We must invalidate our idea of the oldest lsn in all the named slots if
* we might have changed the list.
*/
standby_slot_names_oldest_flush_lsn = InvalidXLogRecPtr;
old_ctx = MemoryContextSwitchTo(TopMemoryContext);
standby_slot_names_string = pstrdup(newval);
(void) SplitIdentifierString(standby_slot_names_string, ',',
&standby_slot_names);
(void) MemoryContextSwitchTo(old_ctx);
}
/*
* Get failover slots from upstream
*/
static List *
remote_get_primary_slot_info(PGconn *conn, List *slot_filter)
{
PGresult *res;
int i;
char *op = "";
List *slots = NIL;
ListCell *lc;
StringInfoData query;
initStringInfo(&query);
if (PQserverVersion(conn) >= 140000)
{
appendStringInfoString(
&query,
"SELECT slot_name, plugin, database, two_phase, catalog_xmin, restart_lsn, confirmed_flush_lsn"
" FROM pg_catalog.pg_replication_slots"
" WHERE database IS NOT NULL AND (");
}
else
{
appendStringInfoString(
&query,
"SELECT slot_name, plugin, database, false AS two_phase, catalog_xmin, restart_lsn, confirmed_flush_lsn"
" FROM pg_catalog.pg_replication_slots"
" WHERE database IS NOT NULL AND (");
}
foreach (lc, slot_filter)
{
FailoverSlotFilter *filter = lfirst(lc);
switch (filter->key)
{
case FAILOVERSLOT_FILTER_NAME:
appendStringInfo(
&query, " %s slot_name OPERATOR(pg_catalog.=) %s", op,
PQescapeLiteral(conn, filter->val, strlen(filter->val)));
break;
case FAILOVERSLOT_FILTER_NAME_LIKE:
appendStringInfo(
&query, " %s slot_name LIKE %s", op,
PQescapeLiteral(conn, filter->val, strlen(filter->val)));
break;
case FAILOVERSLOT_FILTER_PLUGIN:
appendStringInfo(
&query, " %s plugin OPERATOR(pg_catalog.=) %s", op,
PQescapeLiteral(conn, filter->val, strlen(filter->val)));
break;
default:
Assert(0);
elog(ERROR, "unrecognized slot filter key %u", filter->key);
}
op = "OR";
}
appendStringInfoString(&query, ")");
res = PQexec(conn, query.data);
pfree(query.data);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
elog(ERROR, "could not fetch slot information from provider: %s\n",
res != NULL ? PQresultErrorMessage(res) : PQerrorMessage(conn));
for (i = 0; i < PQntuples(res); i++)
{
RemoteSlot *slot = palloc0(sizeof(RemoteSlot));
slot->name = pstrdup(PQgetvalue(res, i, 0));
slot->plugin = pstrdup(PQgetvalue(res, i, 1));
slot->database = pstrdup(PQgetvalue(res, i, 2));
parse_bool(PQgetvalue(res, i, 3), &slot->two_phase);
slot->catalog_xmin = !PQgetisnull(res, i, 4) ?
atoi(PQgetvalue(res, i, 4)) :
InvalidTransactionId;
slot->restart_lsn =
!PQgetisnull(res, i, 5) ?
DatumGetLSN(DirectFunctionCall1(
pg_lsn_in, CStringGetDatum(PQgetvalue(res, i, 5)))) :
InvalidXLogRecPtr;
slot->confirmed_lsn =
!PQgetisnull(res, i, 6) ?
DatumGetLSN(DirectFunctionCall1(
pg_lsn_in, CStringGetDatum(PQgetvalue(res, i, 6)))) :
InvalidXLogRecPtr;
slots = lappend(slots, slot);
}
PQclear(res);
return slots;
}
static XLogRecPtr
remote_get_physical_slot_lsn(PGconn *conn, const char *slot_name)
{
PGresult *res;
XLogRecPtr lsn;
StringInfoData query;
initStringInfo(&query);
appendStringInfo(&query,
"SELECT restart_lsn"
" FROM pg_catalog.pg_replication_slots"
" WHERE slot_name OPERATOR(pg_catalog.=) %s",
PQescapeLiteral(conn, slot_name, strlen(slot_name)));
res = PQexec(conn, query.data);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
elog(ERROR, "could not fetch slot information from provider: %s\n",
res != NULL ? PQresultErrorMessage(res) : PQerrorMessage(conn));
if (PQntuples(res) != 1)
elog(ERROR, "physical slot %s not found on primary", slot_name);
if (PQgetisnull(res, 0, 0))
lsn = InvalidXLogRecPtr;
else
lsn = DatumGetLSN(DirectFunctionCall1(
pg_lsn_in, CStringGetDatum(PQgetvalue(res, 0, 0))));
PQclear(res);
return lsn;
}
/*
* Can't use get_database_oid from dbcommands.c because it does not work
* without db connection.
*/
static Oid
get_database_oid(const char *dbname)
{
HeapTuple tuple;
Relation relation;
SysScanDesc scan;
ScanKeyData key[1];
Oid dboid = InvalidOid;
/*
* form a scan key
*/
ScanKeyInit(&key[0], Anum_pg_database_datname, BTEqualStrategyNumber,
F_NAMEEQ, CStringGetDatum(dbname));
/*
* Open pg_database and fetch a tuple. Force heap scan if we haven't yet
* built the critical shared relcache entries (i.e., we're starting up
* without a shared relcache cache file).
*/
relation = table_open(DatabaseRelationId, AccessShareLock);
scan = systable_beginscan(relation, DatabaseNameIndexId,
criticalSharedRelcachesBuilt, NULL, 1, key);
tuple = systable_getnext(scan);
/* Must copy tuple before releasing buffer */
if (HeapTupleIsValid(tuple))
#if PG_VERSION_NUM < 120000
dboid = HeapTupleGetOid(tuple);
#else
{
Form_pg_database datForm = (Form_pg_database) GETSTRUCT(tuple);
dboid = datForm->oid;
}
#endif
else
ereport(ERROR, (errcode(ERRCODE_UNDEFINED_DATABASE),
errmsg("database \"%s\" does not exist", dbname)));
/* all done */
systable_endscan(scan);
table_close(relation, AccessShareLock);
return dboid;
}
/*
* Fill connection string info based on config.
*
* This is slightly complicated because we default to primary_conninfo if
* user didn't explicitly set anything and we might need to request explicit
* database name override, that's why we need dedicated function for this.
*/
static void
make_sync_failover_slots_dsn(StringInfo connstr, char *db_name)
{
if (spock_failover_slots_dsn && strlen(spock_failover_slots_dsn) > 0)
{
if (db_name)
appendStringInfo(connstr, "%s dbname=%s", spock_failover_slots_dsn,
db_name);
else
appendStringInfoString(connstr, spock_failover_slots_dsn);
}
else
{
Assert(WalRcv);
appendStringInfo(connstr, "%s dbname=%s", WalRcv->conninfo,
db_name ? db_name : "postgres");
}
}
/*
* Connect to remote pg server
*/
static PGconn *
remote_connect(const char *connstr, const char *appname)
{
#define CONN_PARAM_ARRAY_SIZE 8
int i = 0;
PGconn *conn;
const char *keys[CONN_PARAM_ARRAY_SIZE];
const char *vals[CONN_PARAM_ARRAY_SIZE];
StringInfoData s;
initStringInfo(&s);
appendStringInfoString(&s, connstr);
keys[i] = "dbname";
vals[i] = connstr;
i++;
keys[i] = "application_name";
vals[i] = appname;
i++;
keys[i] = "connect_timeout";
vals[i] = "30";
i++;
keys[i] = "keepalives";
vals[i] = "1";
i++;
keys[i] = "keepalives_idle";
vals[i] = "20";
i++;
keys[i] = "keepalives_interval";
vals[i] = "20";
i++;
keys[i] = "keepalives_count";
vals[i] = "5";
i++;
keys[i] = NULL;
vals[i] = NULL;
Assert(i <= CONN_PARAM_ARRAY_SIZE);
/*
* We use the expand_dbname parameter to process the connection string
* (or URI), and pass some extra options.
*/
conn = PQconnectdbParams(keys, vals, /* expand_dbname = */ true);
if (PQstatus(conn) != CONNECTION_OK)
{
ereport(ERROR,
(errmsg("could not connect to the postgresql server: %s",
PQerrorMessage(conn)),
errdetail("dsn was: %s", s.data)));
}
resetStringInfo(&s);
elog(DEBUG2, "established connection to remote backend with pid %d",
PQbackendPID(conn));
return conn;
}
/*
* Wait for remote slot to pass locally reserved position.
*
* Wait until the slot named in 'remote_slot' on the host at 'conn' has all its
* requirements satisfied by the local slot 'slot' by polling 'conn'. This
* relies on us having already reserved the WAL for the old position of
* `remote_slot` so `slot` can't continue to advance.
*/
static bool
wait_for_primary_slot_catchup(ReplicationSlot *slot, RemoteSlot *remote_slot)
{
List *slots;
PGconn *conn;
StringInfoData connstr;
TimestampTz cb_wait_start =
0; /* first invocation should happen immediately */
elog(
LOG,
"waiting for remote slot %s lsn (%X/%X) and catalog xmin (%u) to pass local slot lsn (%X/%X) and catalog xmin (%u)",
remote_slot->name, (uint32) (remote_slot->restart_lsn >> 32),
(uint32) (remote_slot->restart_lsn), remote_slot->catalog_xmin,
(uint32) (slot->data.restart_lsn >> 32),
(uint32) (slot->data.restart_lsn), slot->data.catalog_xmin);
initStringInfo(&connstr);
/*
* Append the dbname of the remote slot. We don't use a generic db
* like postgres here because plugin callback bellow might want to invoke
* extension functions.
*/
make_sync_failover_slots_dsn(&connstr, remote_slot->database);
conn = remote_connect(connstr.data, "spock_failover_slots");
pfree(connstr.data);
for (;;)
{
RemoteSlot *new_slot;
int rc;
FailoverSlotFilter *filter = palloc(sizeof(FailoverSlotFilter));
XLogRecPtr receivePtr;
CHECK_FOR_INTERRUPTS();
if (!RecoveryInProgress())
{
/*
* The remote slot didn't pass the locally reserved position
* at the time of local promotion, so it's not safe to use.
*/
ereport(
WARNING,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg(
"replication slot sync wait for slot %s interrupted by promotion",
remote_slot->name)));
PQfinish(conn);
return false;
}
filter->key = FAILOVERSLOT_FILTER_NAME;
filter->val = remote_slot->name;
slots = remote_get_primary_slot_info(conn, list_make1(filter));
if (!list_length(slots))
{
/* Slot on provider vanished */
PQfinish(conn);
return false;
}
receivePtr = GetWalRcvFlushRecPtr(NULL, NULL);
Assert(list_length(slots) == 1);
new_slot = linitial(slots);
if (new_slot->restart_lsn > receivePtr)
new_slot->restart_lsn = receivePtr;
if (new_slot->confirmed_lsn > receivePtr)
new_slot->confirmed_lsn = receivePtr;
if (new_slot->restart_lsn >= slot->data.restart_lsn &&
TransactionIdFollowsOrEquals(new_slot->catalog_xmin,
MyReplicationSlot->data.catalog_xmin))
{
remote_slot->restart_lsn = new_slot->restart_lsn;
remote_slot->confirmed_lsn = new_slot->confirmed_lsn;
remote_slot->catalog_xmin = new_slot->catalog_xmin;
PQfinish(conn);
return true;
}
/*
* Invoke any callbacks that will help move the slots along
*/
if (TimestampDifferenceExceeds(
cb_wait_start, GetCurrentTimestamp(),
Min(wal_retrieve_retry_interval * 5, PG_WAIT_EXTENSION)))
{
if (cb_wait_start > 0)
elog(
LOG,
"still waiting for remote slot %s lsn (%X/%X) and catalog xmin (%u) to pass local slot lsn (%X/%X) and catalog xmin (%u)",
remote_slot->name, (uint32) (new_slot->restart_lsn >> 32),
(uint32) (new_slot->restart_lsn), new_slot->catalog_xmin,
(uint32) (slot->data.restart_lsn >> 32),
(uint32) (slot->data.restart_lsn),
slot->data.catalog_xmin);
cb_wait_start = GetCurrentTimestamp();
}
rc =
WaitLatch(MyLatch, WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
wal_retrieve_retry_interval, PG_WAIT_EXTENSION);
if (rc & WL_POSTMASTER_DEATH)
proc_exit(1);
ResetLatch(MyLatch);
}
}
/*
* Synchronize one logical replication slot's state from the master to this
* standby, creating it if necessary.
*
* Note that this only works safely because we know for sure that this is
* executed on standby where primary has another slot which reserves resources
* at the position to which we are moving the local slot to.
*
* This standby uses a physical replication slot to connect to the master so it
* can send the xmin and catalog_xmin separately over hot_standby_feedback. Our
* physical slot on the master ensures the master's catalog_xmin never goes
* below ours after the initial setup period.
*/
static void
synchronize_one_slot(RemoteSlot *remote_slot)
{
int i;
bool found = false;
if (!RecoveryInProgress())
{
/* Should only happen when promotion occurs at the same time we sync */
ereport(
WARNING,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg(
"attempted to sync slot from master when not in recovery")));
return;
}
SetCurrentStatementStartTimestamp();
StartTransactionCommand();
PushActiveSnapshot(GetTransactionSnapshot());
/* Search for the named slot locally */
LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
for (i = 0; i < max_replication_slots; i++)
{
ReplicationSlot *s = &ReplicationSlotCtl->replication_slots[i];
/* Not in use, not interesting. */
if (!s->in_use)
continue;
if (strcmp(NameStr(s->data.name), remote_slot->name) == 0)
{
found = true;
break;
}
}
LWLockRelease(ReplicationSlotControlLock);
/*
* Remote slot exists locally, acquire and move. There's a race here where
* the slot could've been dropped since we checked, but we'll just ERROR
* out in `ReplicationSlotAcquire` and retry next loop so it's harmless.
*
* Moving the slot this way does not do logical decoding. We're not
* processing WAL, we're just updating the slot metadata.
*/
if (found)
{
ReplicationSlotAcquire(remote_slot->name, true);
/*
* We can't satisfy this remote slot's requirements with our known-safe
* local restart_lsn, catalog_xmin and xmin.
*
* This shouldn't happen for existing slots unless someone else messed
* with our physical replication slot on the master.
*/
if (remote_slot->restart_lsn < MyReplicationSlot->data.restart_lsn ||
TransactionIdPrecedes(remote_slot->catalog_xmin,
MyReplicationSlot->data.catalog_xmin))
{
elog(
WARNING,
"not synchronizing slot %s; synchronization would move it backward",
remote_slot->name);
ReplicationSlotRelease();
PopActiveSnapshot();
CommitTransactionCommand();
return;
}
LogicalConfirmReceivedLocation(remote_slot->confirmed_lsn);
LogicalIncreaseXminForSlot(remote_slot->confirmed_lsn,
remote_slot->catalog_xmin);
LogicalIncreaseRestartDecodingForSlot(remote_slot->confirmed_lsn,
remote_slot->restart_lsn);
ReplicationSlotMarkDirty();
ReplicationSlotSave();
elog(
DEBUG2,
"synchronized existing slot %s to lsn (%X/%X) and catalog xmin (%u)",
remote_slot->name, (uint32) (remote_slot->restart_lsn >> 32),
(uint32) (remote_slot->restart_lsn), remote_slot->catalog_xmin);
}
/*
* Otherwise create the local slot and initialize it to the state of the
* upstream slot. There's a race here where the slot could've been
* concurrently created, but we'll just ERROR out and retry so it's
* harmless.
*/
else
{
TransactionId xmin_horizon = InvalidTransactionId;
ReplicationSlot *slot;
/*
* We have to create the slot to reserve its name and resources, but
* don't want it to persist if we fail.
*/
#if PG_VERSION_NUM >= 140000
ReplicationSlotCreate(remote_slot->name, true, RS_EPHEMERAL,
remote_slot->two_phase);
#else
ReplicationSlotCreate(remote_slot->name, true, RS_EPHEMERAL);
#endif
slot = MyReplicationSlot;
SpinLockAcquire(&slot->mutex);
slot->data.database = get_database_oid(remote_slot->database);
strlcpy(NameStr(slot->data.plugin), remote_slot->plugin, NAMEDATALEN);
SpinLockRelease(&slot->mutex);
/*
* Stop our physical slot from advancing past the position needed
* by the new remote slot by making its reservations locally
* effective. It's OK if we can't guarantee their safety yet,
* the slot isn't visible to anyone else at this point.
*/
ReplicationSlotReserveWal();
LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
xmin_horizon = GetOldestSafeDecodingTransactionId(true);
slot->effective_catalog_xmin = xmin_horizon;
slot->data.catalog_xmin = xmin_horizon;
ReplicationSlotsComputeRequiredXmin(true);
LWLockRelease(ProcArrayLock);
/*
* Our xmin and/or catalog_xmin may be > that required by one or more
* of the slots we are trying to sync from the master, and/or we don't
* have enough retained WAL for the slot's restart_lsn.
*
* If we persist the slot locally in that state it'll make a false
* promise we can't satisfy.
*
* This can happen if this replica is fairly new or has only recently
* started failover slot sync.
*
* TODO: Don't stop synchronization of other slots for this, we can't
* add timeout because that could result in some slots never being
* synchronized as they will always be behind the physical slot.
*/
if (remote_slot->restart_lsn < MyReplicationSlot->data.restart_lsn ||
TransactionIdPrecedes(remote_slot->catalog_xmin,
MyReplicationSlot->data.catalog_xmin))
{
if (!wait_for_primary_slot_catchup(MyReplicationSlot, remote_slot))
{
/* Provider slot didn't catch up to locally reserved position
*/
ReplicationSlotRelease();
PopActiveSnapshot();
CommitTransactionCommand();
return;
}
}
/*
* We can locally satisfy requirements of remote slot's current
* position now. Apply the new position if any and make it persistent.
*/
LogicalConfirmReceivedLocation(remote_slot->confirmed_lsn);
LogicalIncreaseXminForSlot(remote_slot->confirmed_lsn,
remote_slot->catalog_xmin);
LogicalIncreaseRestartDecodingForSlot(remote_slot->confirmed_lsn,
remote_slot->restart_lsn);
ReplicationSlotMarkDirty();
ReplicationSlotPersist();
elog(DEBUG1,
"synchronized new slot %s to lsn (%X/%X) and catalog xmin (%u)",
remote_slot->name, (uint32) (remote_slot->restart_lsn >> 32),
(uint32) (remote_slot->restart_lsn), remote_slot->catalog_xmin);
}
ReplicationSlotRelease();
PopActiveSnapshot();
CommitTransactionCommand();
}
/*
* Synchronize the slot states from master to standby.
*
* This logic emulates the "failover slots" behaviour unsuccessfully proposed
* for 9.6 using the PostgreSQL 10 features "catalog xmin in hot standby
* feedback" and "logical decoding follows timeline switches".
*
* This is only called in recovery from main loop of manager and only in PG10+
* because in older versions the manager worker uses
* bgw_start_time = BgWorkerStart_RecoveryFinished.
*
* We could technically synchronize slot positions even on older versions of
* PostgreSQL but since logical decoding can't go over the timeline switch
* before PG10, it's pointless to have slots synchronized. Also, older versions
* can't keep catalog_xmin separate from xmin in hot standby feedback, so
* sending the feedback we need to preserve our catalog_xmin could cause severe
* table bloat on the master.
*
* This runs periodically. That's safe when the slots on the master already
* exist locally because we have their resources reserved via hot standby
* feedback. New subscriptions can't move that position backwards... but we
* won't immediately know they exist when the master creates them. So there's a
* window after each new subscription is created on the master where failover
* to this standby will break that subscription.
*/
static long
synchronize_failover_slots(long sleep_time)
{
List *slots;
ListCell *lc;
PGconn *conn;
XLogRecPtr safe_lsn;
XLogRecPtr lsn = InvalidXLogRecPtr;
static bool was_lsn_safe = false;
bool is_lsn_safe = false;
StringInfoData connstr;
if (!WalRcv || !HotStandbyActive() ||
list_length(spock_failover_slot_names_list) == 0)
return sleep_time;
/* XXX should these be errors or just soft return like above? */
if (!hot_standby_feedback)
elog(
ERROR,
"cannot synchronize replication slot positions because hot_standby_feedback is off");
if (WalRcv->slotname[0] == '\0')
elog(
ERROR,
"cannot synchronize replication slot positions because primary_slot_name is not set");
elog(DEBUG1, "starting replication slot synchronization from primary");
initStringInfo(&connstr);
make_sync_failover_slots_dsn(&connstr, NULL /* Use default db name */);
conn = remote_connect(connstr.data, "spock_failover_slots");
/*
* Do not synchronize WAL decoder slots on a physical standy.
*
* WAL decoder slots are used to produce LCRs. These LCRs are not
* synchronized on a physical standby after initial backup and hence are
* not included in the base backup. Thus WAL decoder slots, if synchronized
* on physical standby, do not reflect the status of LCR directory as they
* do on primary.
*
* There are other slots whose WAL senders use LCRs. These other slots are
* synchronized and used after promotion. Since the WAL decoder slots are
* ahead of these other slots, the WAL decoder when started after promotion
* might miss LCRs required by WAL senders of the other slots. This would
* cause data inconsistency after promotion.
*
* Hence do not synchronize WAL decoder slot. Those will be created after
* promotion
*/
slots = remote_get_primary_slot_info(conn, spock_failover_slot_names_list);
safe_lsn = remote_get_physical_slot_lsn(conn, WalRcv->slotname);
/*
* Delete locally-existing slots that don't exist on the master.
*/
for (;;)
{
int i;
char *dropslot = NULL;
LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
for (i = 0; i < max_replication_slots; i++)
{
ReplicationSlot *s = &ReplicationSlotCtl->replication_slots[i];
bool active;
bool found = false;
active = (s->active_pid != 0);
/* Only check inactive slots. */
if (!s->in_use || active)
continue;
/* Only check for logical slots. */
if (SlotIsPhysical(s))
continue;
/* Try to find slot in slots returned by primary. */
foreach (lc, slots)
{
RemoteSlot *remote_slot = lfirst(lc);
if (strcmp(NameStr(s->data.name), remote_slot->name) == 0)
{
found = true;
break;
}
}
/*
* Not found, should be dropped if synchronize_failover_slots_drop
* is enabled.
*/
if (!found && spock_failover_slots_drop)
{
dropslot = pstrdup(NameStr(s->data.name));
break;
}
}
LWLockRelease(ReplicationSlotControlLock);
if (dropslot)
{
elog(WARNING, "dropping replication slot \"%s\"", dropslot);
ReplicationSlotDrop(dropslot, false);
pfree(dropslot);
}
else
break;
}
if (!list_length(slots))
{
PQfinish(conn);
return sleep_time;
}
/* Find oldest restart_lsn still needed by any failover slot. */
foreach (lc, slots)
{
RemoteSlot *remote_slot = lfirst(lc);
if (lsn == InvalidXLogRecPtr || remote_slot->restart_lsn < lsn)
lsn = remote_slot->restart_lsn;
}