forked from 2ndQuadrant/bdr
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbdr_locks.c
More file actions
1765 lines (1444 loc) · 49.1 KB
/
Copy pathbdr_locks.c
File metadata and controls
1765 lines (1444 loc) · 49.1 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
/* -------------------------------------------------------------------------
*
* bdr_locks.c
* global ddl/dml interlocking locks
*
*
* Copyright (C) 2014-2015, PostgreSQL Global Development Group
*
* NOTES
*
* A relatively simple distributed DDL locking implementation:
*
* Locks are acquired on a database granularity and can only be held by a
* single node. That choice was made to reduce both, the complexity of the
* implementation, and to reduce the likelihood of inter node deadlocks.
*
* Because DDL locks have to acquired inside transactions the inter node
* communication can't be done via a queue table streamed out via logical
* decoding - other nodes would only see the result once the the
* transaction commits... Instead the 'messaging' feature is used which
* allows to inject transactional and nontransactional messages in the
* changestream.
*
* There are really two levels of DDL lock - the global lock that only
* one node can hold, and individual local DDL locks on each node. If
* a node holds the global DDL lock then it owns the local DDL locks on each
* node.
*
* DDL lock acquiration basically works like this:
*
* 1) A utility command notices that it needs the global ddl lock and the local
* node doesn't already hold it. If there already is a local ddl lock
* it'll ERROR out, as this indicates another node already holds or is
* trying to acquire the global DDL lock.
*
* 2) It sends out a 'acquire_lock' message to all other nodes.
*
* 3) When another node receives a 'acquire_lock' message it checks whether
* the local ddl lock is already held. If so it'll send a 'decline_lock'
* message back causing the lock acquiration to fail.
*
* 4) If a 'acquire_lock' message is received and the local DDL lock is not
* held it'll be acquired and an entry into the 'bdr_global_locks' table
* will be made marking the lock to be in the 'catchup' phase.
*
* 5) All concurrent user transactions will be cancelled (after a grace period,
* and if DML write cancel is required for this lock type).
*
* 6) A 'request_replay_confirm' message will be sent to all other nodes
* containing a lsn that has to be replayed.
*
* 7) When a 'request_replay_confirm' message is received, a
* 'replay_confirm' message will be sent back.
*
* 8) Once all other nodes have replied with 'replay_confirm' the DDL lock
* has been successfully acquired on the node reading the 'acquire_lock'
* message (from 3)). The corresponding bdr_global_locks entry will be
* updated to the 'acquired' state and a 'confirm_lock' message will be sent out.
*
* 9) Once all nodes have replied with 'confirm_lock' messages the ddl lock
* has been acquired.
*
* There's some additional complications to handle crash safety:
*
* Everytime a node crashes it sends out a 'startup' message causing all
* other nodes to release locks held by it before the crash.
* Then the bdr_global_locks table is read. All existing locks are
* acquired. If a lock still is in 'catchup' phase the lock acquiration
* process is re-started at step 6)
*
* IDENTIFICATION
* bdr_locks.c
*
* -------------------------------------------------------------------------
*/
#include "postgres.h"
#include "bdr.h"
#include "bdr_locks.h"
#include "miscadmin.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "commands/dbcommands.h"
#include "catalog/indexing.h"
#include "executor/executor.h"
#include "libpq/pqformat.h"
#include "replication/replication_identifier.h"
#include "replication/slot.h"
#include "storage/barrier.h"
#include "storage/ipc.h"
#include "storage/lwlock.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "storage/shmem.h"
#include "storage/sinvaladt.h"
#include "storage/standby.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/snapmgr.h"
#define LOCKTRACE "DDL LOCK TRACE: "
/* GUCs */
bool bdr_permit_ddl_locking = false;
/* -1 means use max_standby_streaming_delay */
int bdr_max_ddl_lock_delay = -1;
/* -1 means use lock_timeout/statement_timeout */
int bdr_ddl_lock_timeout = -1;
typedef struct BDRLockWaiter {
PGPROC *proc;
slist_node node;
} BDRLockWaiter;
typedef struct BdrLocksDBState {
/* db slot used */
bool in_use;
/* db this slot is reserved for */
Oid dboid;
/* number of nodes we're connected to */
Size nnodes;
/* has startup progressed far enough to allow writes? */
bool locked_and_loaded;
int lockcount;
RepNodeId lock_holder;
BDRLockType lock_type;
/* progress of lock acquiration */
int acquire_confirmed;
int acquire_declined;
/* progress of replay confirmation */
int replay_confirmed;
XLogRecPtr replay_confirmed_lsn;
Latch *requestor;
slist_head waiters; /* list of waiting PGPROCs */
} BdrLocksDBState;
typedef struct BdrLocksCtl {
LWLock *lock;
BdrLocksDBState *dbstate;
BDRLockWaiter *waiters;
} BdrLocksCtl;
static BdrLocksDBState * bdr_locks_find_database(Oid dbid, bool create);
static void bdr_locks_find_my_database(bool create);
static void bdr_prepare_message(StringInfo s, BdrMessageType message_type);
static char *bdr_lock_type_to_name(BDRLockType lock_type);
static BDRLockType bdr_lock_name_to_type(const char *lock_type);
static void bdr_request_replay_confirmation(void);
static void bdr_send_confirm_lock(void);
static void bdr_locks_addwaiter(PGPROC *proc);
static void bdr_locks_on_unlock(void);
static int ddl_lock_log_level(int);
static BdrLocksCtl *bdr_locks_ctl;
/* shmem init hook to chain to on startup, if any */
static shmem_startup_hook_type prev_shmem_startup_hook = NULL;
/* this database's state */
static BdrLocksDBState *bdr_my_locks_database = NULL;
static bool this_xact_acquired_lock = false;
static size_t
bdr_locks_shmem_size(void)
{
Size size = 0;
uint32 TotalProcs = MaxBackends + NUM_AUXILIARY_PROCS;
size = add_size(size, sizeof(BdrLocksCtl));
size = add_size(size, mul_size(sizeof(BdrLocksDBState), bdr_max_databases));
size = add_size(size, mul_size(sizeof(BDRLockWaiter), TotalProcs));
return size;
}
static void
bdr_locks_shmem_startup(void)
{
bool found;
if (prev_shmem_startup_hook != NULL)
prev_shmem_startup_hook();
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
bdr_locks_ctl = ShmemInitStruct("bdr_locks",
bdr_locks_shmem_size(),
&found);
if (!found)
{
memset(bdr_locks_ctl, 0, bdr_locks_shmem_size());
bdr_locks_ctl->lock = LWLockAssign();
bdr_locks_ctl->dbstate = (BdrLocksDBState *) bdr_locks_ctl + sizeof(BdrLocksCtl);
bdr_locks_ctl->waiters = (BDRLockWaiter *) bdr_locks_ctl + sizeof(BdrLocksCtl) +
mul_size(sizeof(BdrLocksDBState), bdr_max_databases);
}
LWLockRelease(AddinShmemInitLock);
}
/* Needs to be called from a shared_preload_library _PG_init() */
void
bdr_locks_shmem_init()
{
/* Must be called from postmaster its self */
Assert(IsPostmasterEnvironment && !IsUnderPostmaster);
bdr_locks_ctl = NULL;
RequestAddinShmemSpace(bdr_locks_shmem_size());
RequestAddinLWLocks(1);
prev_shmem_startup_hook = shmem_startup_hook;
shmem_startup_hook = bdr_locks_shmem_startup;
}
/* Waiter manipulation. */
void
bdr_locks_addwaiter(PGPROC *proc)
{
BDRLockWaiter *waiter = &bdr_locks_ctl->waiters[proc->pgprocno];
waiter->proc = proc;
slist_push_head(&bdr_my_locks_database->waiters, &waiter->node);
elog(ddl_lock_log_level(DDL_LOCK_TRACE_DEBUG), LOCKTRACE "backend started waiting on DDL lock");
}
void
bdr_locks_on_unlock(void)
{
while (!slist_is_empty(&bdr_my_locks_database->waiters))
{
slist_node *node;
BDRLockWaiter *waiter;
PGPROC *proc;
node = slist_pop_head_node(&bdr_my_locks_database->waiters);
waiter = slist_container(BDRLockWaiter, node, node);
proc = waiter->proc;
SetLatch(&proc->procLatch);
}
}
/*
* Turn a DDL lock level into an elog level using the bdr.ddl_lock_trace_level
* setting.
*/
static int
ddl_lock_log_level(int ddl_lock_trace_level)
{
return ddl_lock_trace_level >= bdr_trace_ddl_locks_level ? LOG : DEBUG1;
}
/*
* Find, and create if necessary, the lock state entry for dboid.
*/
static BdrLocksDBState*
bdr_locks_find_database(Oid dboid, bool create)
{
int off;
int free_off = -1;
for(off = 0; off < bdr_max_databases; off++)
{
BdrLocksDBState *db = &bdr_locks_ctl->dbstate[off];
if (db->in_use && db->dboid == MyDatabaseId)
{
bdr_my_locks_database = db;
return db;
}
if (!db->in_use && free_off == -1)
free_off = off;
}
if (!create)
/*
* We can't call get_databse_name here as the catalogs may not be
* accessible, so we can only report the oid of the database.
*/
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("database with oid=%u is not configured for bdr or bdr is still starting up",
dboid)));
if (free_off != -1)
{
BdrLocksDBState *db = &bdr_locks_ctl->dbstate[free_off];
memset(db, 0, sizeof(BdrLocksDBState));
db->dboid = MyDatabaseId;
db->in_use = true;
return db;
}
ereport(ERROR,
(errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
errmsg("Too many databases BDR-enabled for bdr.max_databases"),
errhint("Increase bdr.max_databases above the current limit of %d", bdr_max_databases)));
}
static void
bdr_locks_find_my_database(bool create)
{
Assert(IsUnderPostmaster);
Assert(OidIsValid(MyDatabaseId));
if (bdr_my_locks_database != NULL)
return;
bdr_my_locks_database = bdr_locks_find_database(MyDatabaseId, create);
Assert(bdr_my_locks_database != NULL);
}
/*
* This node has just started up. Init its local state and send a startup
* announcement message.
*
* Called from the per-db worker.
*/
void
bdr_locks_startup()
{
Relation rel;
ScanKey key;
SysScanDesc scan;
Snapshot snap;
HeapTuple tuple;
XLogRecPtr lsn;
StringInfoData s;
Assert(IsUnderPostmaster);
Assert(!IsTransactionState());
Assert(bdr_worker_type == BDR_WORKER_PERDB);
bdr_locks_find_my_database(true);
/*
* Don't initialize database level lock state twice. An crash requiring
* that has to be severe enough to trigger a crash-restart cycle.
*/
if (bdr_my_locks_database->locked_and_loaded)
return;
slist_init(&bdr_my_locks_database->waiters);
/* We haven't yet established how many nodes we're connected to. */
bdr_my_locks_database->nnodes = 0;
initStringInfo(&s);
/*
* Send restart message causing all other backends to release global locks
* possibly held by us. We don't necessarily remember sending the request
* out.
*/
bdr_prepare_message(&s, BDR_MESSAGE_START);
elog(DEBUG1, "sending global lock startup message");
lsn = LogStandbyMessage(s.data, s.len, false);
resetStringInfo(&s);
XLogFlush(lsn);
/* reacquire all old ddl locks in table */
StartTransactionCommand();
snap = RegisterSnapshot(GetLatestSnapshot());
rel = heap_open(BdrLocksRelid, RowExclusiveLock);
key = (ScanKey) palloc(sizeof(ScanKeyData) * 1);
ScanKeyInit(&key[0],
8,
BTEqualStrategyNumber, F_OIDEQ,
bdr_my_locks_database->dboid);
scan = systable_beginscan(rel, 0, true, snap, 1, key);
/* TODO: support multiple locks */
while ((tuple = systable_getnext(scan)) != NULL)
{
Datum values[10];
bool isnull[10];
const char *state;
uint64 sysid;
RepNodeId node_id;
BDRLockType lock_type;
heap_deform_tuple(tuple, RelationGetDescr(rel),
values, isnull);
/* lookup the lock owner's node id */
state = TextDatumGetCString(values[9]);
if (sscanf(TextDatumGetCString(values[1]), UINT64_FORMAT, &sysid) != 1)
elog(ERROR, "could not parse sysid %s",
TextDatumGetCString(values[1]));
node_id = bdr_fetch_node_id_via_sysid(
sysid, DatumGetObjectId(values[2]), DatumGetObjectId(values[3]));
lock_type = bdr_lock_name_to_type(TextDatumGetCString(values[0]));
if (strcmp(state, "acquired") == 0)
{
bdr_my_locks_database->lock_holder = node_id;
bdr_my_locks_database->lockcount++;
bdr_my_locks_database->lock_type = lock_type;
/* A remote node might have held the local lock before restart */
elog(DEBUG1, "reacquiring local lock held before shutdown");
}
else if (strcmp(state, "catchup") == 0)
{
XLogRecPtr wait_for_lsn;
/*
* Restart the catchup period. There shouldn't be any need to
* kickof sessions here, because we're starting early.
*/
wait_for_lsn = GetXLogInsertRecPtr();
bdr_prepare_message(&s, BDR_MESSAGE_REQUEST_REPLAY_CONFIRM);
pq_sendint64(&s, wait_for_lsn);
lsn = LogStandbyMessage(s.data, s.len, false);
XLogFlush(lsn);
resetStringInfo(&s);
bdr_my_locks_database->lock_holder = node_id;
bdr_my_locks_database->lockcount++;
bdr_my_locks_database->lock_type = lock_type;
bdr_my_locks_database->replay_confirmed = 0;
bdr_my_locks_database->replay_confirmed_lsn = wait_for_lsn;
elog(DEBUG1, "restarting global lock replay catchup phase");
}
else
elog(PANIC, "unknown lockstate '%s'", state);
}
systable_endscan(scan);
UnregisterSnapshot(snap);
heap_close(rel, NoLock);
CommitTransactionCommand();
elog(DEBUG2, "global locking startup completed, local DML enabled");
/* allow local DML */
bdr_my_locks_database->locked_and_loaded = true;
}
void
bdr_locks_set_nnodes(Size nnodes)
{
Assert(IsBackgroundWorker);
Assert(bdr_my_locks_database != NULL);
/*
* XXX DYNCONF No protection against node addition during DDL lock acquire
*
* Node counts are currently grabbed straight from the perdb worker's shmem
* and could change whenever someone adds a worker, with no locking or
* protection.
*
* We could acquire the local DDL lock before setting the nodecount, which
* would cause requests from other nodes to get rejected and cause other
* local tx's to fail to request the global DDL lock. However, we'd have to
* acquire it when we committed to adding the new worker, which happens in
* a user backend, and release it from the perdb worker once the new worker
* is registered. Fragile.
*
* Doing so also fails to solve the other half of the problem, which is
* that DDL locking expects there to be one bdr walsender for each apply
* worker, i.e. each connection should be reciprocal. We could connect to
* the other end and register a connection back to us, but that's getting
* complicated for what's always going to be a temporary option before a
* full part/join protocol is added.
*
* So we're just going to cross our fingers. Worst case is that DDL locking
* gets stuck and we have to restart all the nodes.
*
* The full part/join protocol will solve this by acquiring the DDL lock
* before joining.
*/
bdr_my_locks_database->nnodes = nnodes;
}
static void
bdr_prepare_message(StringInfo s, BdrMessageType message_type)
{
/* channel */
pq_sendint(s, strlen("bdr"), 4);
pq_sendbytes(s, "bdr", strlen("bdr"));
/* message type */
pq_sendint(s, message_type, 4);
/* node identifier */
pq_sendint64(s, GetSystemIdentifier()); /* sysid */
pq_sendint(s, ThisTimeLineID, 4); /* tli */
pq_sendint(s, MyDatabaseId, 4); /* database */
pq_sendint(s, 0, 4); /* name, always empty for now */
/* caller's data will follow */
}
static void
bdr_lock_xact_callback(XactEvent event, void *arg)
{
if (!this_xact_acquired_lock)
return;
if (event == XACT_EVENT_ABORT || event == XACT_EVENT_COMMIT)
{
XLogRecPtr lsn;
StringInfoData s;
elog(ddl_lock_log_level(DDL_LOCK_TRACE_ACQUIRE_RELEASE), LOCKTRACE "releasing owned ddl lock on xact %s",
event == XACT_EVENT_ABORT ? "abort" : "commit");
initStringInfo(&s);
bdr_prepare_message(&s, BDR_MESSAGE_RELEASE_LOCK);
/* no lock_type, finished transaction releases all locks it held */
pq_sendint64(&s, GetSystemIdentifier()); /* sysid */
pq_sendint(&s, ThisTimeLineID, 4); /* tli */
pq_sendint(&s, MyDatabaseId, 4); /* database */
/* no name! locks are db wide */
lsn = LogStandbyMessage(s.data, s.len, false);
XLogFlush(lsn);
LWLockAcquire(bdr_locks_ctl->lock, LW_EXCLUSIVE);
if (bdr_my_locks_database->lockcount > 0)
bdr_my_locks_database->lockcount--;
else
elog(WARNING, "Releasing unacquired global lock");
this_xact_acquired_lock = false;
bdr_my_locks_database->lock_type = BDR_LOCK_NOLOCK;
bdr_my_locks_database->replay_confirmed = 0;
bdr_my_locks_database->replay_confirmed_lsn = InvalidXLogRecPtr;
bdr_my_locks_database->requestor = NULL;
if (bdr_my_locks_database->lockcount == 0)
bdr_locks_on_unlock();
LWLockRelease(bdr_locks_ctl->lock);
}
}
static void
register_xact_callback()
{
static bool registered;
if (!registered)
{
RegisterXactCallback(bdr_lock_xact_callback, NULL);
registered = true;
}
}
static SysScanDesc
locks_begin_scan(Relation rel, Snapshot snap, uint64 sysid, TimeLineID tli, Oid datid)
{
ScanKey key;
char buf[30];
key = (ScanKey) palloc(sizeof(ScanKeyData) * 4);
sprintf(buf, UINT64_FORMAT, sysid);
ScanKeyInit(&key[0],
2,
BTEqualStrategyNumber, F_TEXTEQ,
CStringGetTextDatum(buf));
ScanKeyInit(&key[1],
3,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(tli));
ScanKeyInit(&key[2],
4,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(datid));
return systable_beginscan(rel, 0, true, snap, 3, key);
}
/*
* Acquire DDL lock on the side that wants to perform DDL.
*
* Called from a user backend when the command filter spots a DDL attempt; runs
* in the user backend.
*/
void
bdr_acquire_ddl_lock(BDRLockType lock_type)
{
XLogRecPtr lsn;
StringInfoData s;
Assert(IsTransactionState());
/* Not called from within a BDR worker */
Assert(bdr_worker_type == BDR_WORKER_EMPTY_SLOT);
/* We don't support other types of the lock yet. */
Assert(lock_type == BDR_LOCK_DDL || lock_type == BDR_LOCK_WRITE);
bdr_locks_find_my_database(false);
/* No need to do anything if already holding requested lock. */
if (this_xact_acquired_lock &&
bdr_my_locks_database->lock_type >= lock_type)
return;
/*
* If this is the first time in current transaction that we are trying to
* acquire DDL lock, do the sanity checking first.
*/
if (!this_xact_acquired_lock)
{
if (!bdr_permit_ddl_locking)
{
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("Global DDL locking attempt rejected by configuration"),
errdetail("bdr.permit_ddl_locking is false and the attempted command "
"would require the global lock to be acquired. "
"Command rejected."),
errhint("See the 'DDL replication' chapter of the documentation.")));
}
if (bdr_my_locks_database->nnodes == 0)
{
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("No peer nodes or peer node count unknown, cannot acquire global lock"),
errhint("BDR is probably still starting up, wait a while")));
}
}
if (this_xact_acquired_lock)
{
elog(ddl_lock_log_level(DDL_LOCK_TRACE_STATEMENT),
LOCKTRACE "attempting to acquire in mode <%s> (upgrading from <%s>) for (" BDR_LOCALID_FORMAT ")",
bdr_lock_type_to_name(lock_type),
bdr_lock_type_to_name(bdr_my_locks_database->lock_type),
BDR_LOCALID_FORMAT_ARGS);
}
else
{
elog(ddl_lock_log_level(DDL_LOCK_TRACE_STATEMENT),
LOCKTRACE "attempting to acquire in mode <%s> for (" BDR_LOCALID_FORMAT ")",
bdr_lock_type_to_name(lock_type),
BDR_LOCALID_FORMAT_ARGS);
}
/* register an XactCallback to release the lock */
register_xact_callback();
LWLockAcquire(bdr_locks_ctl->lock, LW_EXCLUSIVE);
/* check whether the lock can actually be acquired */
if (!this_xact_acquired_lock && bdr_my_locks_database->lockcount > 0)
{
uint64 holder_sysid;
TimeLineID holder_tli;
Oid holder_datid;
bdr_fetch_sysid_via_node_id(bdr_my_locks_database->lock_holder,
&holder_sysid, &holder_tli,
&holder_datid);
elog(ddl_lock_log_level(DDL_LOCK_TRACE_ACQUIRE_RELEASE),
LOCKTRACE "lock already held by (" BDR_LOCALID_FORMAT ")",
holder_sysid, holder_tli, holder_datid, "");
ereport(ERROR,
(errcode(ERRCODE_LOCK_NOT_AVAILABLE),
errmsg("database is locked against ddl by another node"),
errhint("Node ("UINT64_FORMAT",%u,%u) in the cluster is already performing DDL",
holder_sysid, holder_tli, holder_datid)));
}
/* send message about ddl lock */
initStringInfo(&s);
bdr_prepare_message(&s, BDR_MESSAGE_ACQUIRE_LOCK);
/* Add lock type */
pq_sendint(&s, lock_type, 4);
START_CRIT_SECTION();
/*
* NB: We need to setup the state as if we'd have already acquired the
* lock - otherwise concurrent transactions could acquire the lock; and we
* wouldn't send a release message when we fail to fully acquire the lock.
*/
if (!this_xact_acquired_lock)
{
bdr_my_locks_database->lockcount++;
this_xact_acquired_lock = true;
}
bdr_my_locks_database->acquire_confirmed = 0;
bdr_my_locks_database->acquire_declined = 0;
bdr_my_locks_database->requestor = &MyProc->procLatch;
bdr_my_locks_database->lock_type = lock_type;
/* lock looks to be free, try to acquire it */
lsn = LogStandbyMessage(s.data, s.len, false);
XLogFlush(lsn);
END_CRIT_SECTION();
LWLockRelease(bdr_locks_ctl->lock);
/* ---
* Now wait for standbys to ack ddl lock
* ---
*/
elog(ddl_lock_log_level(DDL_LOCK_TRACE_DEBUG),
LOCKTRACE "sent DDL lock mode %s request for (" BDR_LOCALID_FORMAT "), waiting for confirmation",
bdr_lock_type_to_name(lock_type),
BDR_LOCALID_FORMAT_ARGS);
while (true)
{
int rc;
ResetLatch(&MyProc->procLatch);
LWLockAcquire(bdr_locks_ctl->lock, LW_EXCLUSIVE);
/* check for confirmations in shared memory */
if (bdr_my_locks_database->acquire_declined > 0)
{
elog(ddl_lock_log_level(DDL_LOCK_TRACE_ACQUIRE_RELEASE), LOCKTRACE "acquire declined by another node");
ereport(ERROR,
(errcode(ERRCODE_LOCK_NOT_AVAILABLE),
errmsg("could not acquire global lock - another node has declined our lock request"),
errhint("Likely the other node is acquiring the global lock itself.")));
}
/* wait till all have given their consent */
if (bdr_my_locks_database->acquire_confirmed >= bdr_my_locks_database->nnodes)
{
LWLockRelease(bdr_locks_ctl->lock);
break;
}
LWLockRelease(bdr_locks_ctl->lock);
rc = WaitLatch(&MyProc->procLatch,
WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
10000L);
/* emergency bailout if postmaster has died */
if (rc & WL_POSTMASTER_DEATH)
proc_exit(1);
CHECK_FOR_INTERRUPTS();
}
LWLockAcquire(bdr_locks_ctl->lock, LW_EXCLUSIVE);
/* TODO: recheck it's ours */
bdr_my_locks_database->acquire_confirmed = 0;
bdr_my_locks_database->acquire_declined = 0;
bdr_my_locks_database->requestor = NULL;
elog(ddl_lock_log_level(DDL_LOCK_TRACE_ACQUIRE_RELEASE),
LOCKTRACE "DDL lock acquired in mode mode %s (" BDR_LOCALID_FORMAT ")",
bdr_lock_type_to_name(lock_type),
BDR_LOCALID_FORMAT_ARGS);
LWLockRelease(bdr_locks_ctl->lock);
}
static bool
check_is_my_origin_node(uint64 sysid, TimeLineID tli, Oid datid)
{
uint64 replay_sysid;
TimeLineID replay_tli;
Oid replay_datid;
Assert(!IsTransactionState());
StartTransactionCommand();
bdr_fetch_sysid_via_node_id(replication_origin_id, &replay_sysid,
&replay_tli, &replay_datid);
CommitTransactionCommand();
if (sysid != replay_sysid ||
tli != replay_tli ||
datid != replay_datid)
return false;
return true;
}
static bool
check_is_my_node(uint64 sysid, TimeLineID tli, Oid datid)
{
if (sysid != GetSystemIdentifier() ||
tli != ThisTimeLineID ||
datid != MyDatabaseId)
return false;
return true;
}
/*
* Kill any writing transactions while giving them some grace period for
* finishing.
*
* Caller is responsible for ensuring that no new writes can be started during
* the execution of this function.
*/
static bool
cancel_conflicting_transactions(void)
{
VirtualTransactionId *conflict;
TimestampTz killtime,
canceltime;
int waittime = 1000;
killtime = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
bdr_max_ddl_lock_delay > 0 ?
bdr_max_ddl_lock_delay : max_standby_streaming_delay);
if (bdr_ddl_lock_timeout > 0 || LockTimeout > 0)
canceltime = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
bdr_ddl_lock_timeout > 0 ? bdr_ddl_lock_timeout : LockTimeout);
else
TIMESTAMP_NOEND(canceltime);
conflict = GetConflictingVirtualXIDs(InvalidTransactionId, MyDatabaseId);
while (conflict->backendId != InvalidBackendId)
{
PGPROC *pgproc = BackendIdGetProc(conflict->backendId);
PGXACT *pgxact;
if (pgproc == NULL)
continue;
pgxact = &ProcGlobal->allPgXact[pgproc->pgprocno];
/* Skip the transactions that didn't do any writes. */
if (!TransactionIdIsValid(pgxact->xid))
{
conflict++;
continue;
}
/* If here is writing transaction give it time to finish */
if (!TIMESTAMP_IS_NOEND(canceltime) &&
GetCurrentTimestamp() < canceltime)
{
return false;
}
else if (GetCurrentTimestamp() < killtime)
{
int rc;
/* Increasing backoff interval for wait time with limit of 1s */
pg_usleep(waittime);
waittime *= 2;
if (waittime > 1000000)
waittime = 1000000;
rc = WaitLatch(&MyProc->procLatch,
WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
waittime);
ResetLatch(&MyProc->procLatch);
/* emergency bailout if postmaster has died */
if (rc & WL_POSTMASTER_DEATH)
proc_exit(1);
}
else
{
/* We reached timeout so lets kill the writing transaction */
pid_t p = CancelVirtualTransaction(*conflict, PROCSIG_RECOVERY_CONFLICT_LOCK);
/*
* Either confirm kill or sleep a bit to prevent the other node
* being busy with signal processing.
*/
if (p == 0)
conflict++;
else
pg_usleep(1000);
elog(ddl_lock_log_level(DDL_LOCK_TRACE_DEBUG),
LOCKTRACE "signalling pid %d to terminate because of global DDL lock acquisition", p);
}
}
return true;
}
static void
bdr_request_replay_confirmation(void)
{
StringInfoData s;
XLogRecPtr lsn,
wait_for_lsn;
initStringInfo(&s);
wait_for_lsn = GetXLogInsertRecPtr();
bdr_prepare_message(&s, BDR_MESSAGE_REQUEST_REPLAY_CONFIRM);
pq_sendint64(&s, wait_for_lsn);
LWLockAcquire(bdr_locks_ctl->lock, LW_EXCLUSIVE);
lsn = LogStandbyMessage(s.data, s.len, false);
XLogFlush(lsn);
bdr_my_locks_database->replay_confirmed = 0;
bdr_my_locks_database->replay_confirmed_lsn = wait_for_lsn;
LWLockRelease(bdr_locks_ctl->lock);
resetStringInfo(&s);
}
/*
* Another node has asked for a DDL lock. Try to acquire the local ddl lock.
*
* Runs in the apply worker.
*/
void
bdr_process_acquire_ddl_lock(uint64 sysid, TimeLineID tli, Oid datid, BDRLockType lock_type)
{
StringInfoData s;
const char *lock_name = bdr_lock_type_to_name(lock_type);
Assert(!IsTransactionState());
Assert(bdr_worker_type == BDR_WORKER_APPLY);
/* Don't care about locks acquired locally. Already held. */
if (!check_is_my_origin_node(sysid, tli, datid))
return;
bdr_locks_find_my_database(false);
elog(ddl_lock_log_level(DDL_LOCK_TRACE_PEERS),
LOCKTRACE "%s lock requested by node ("UINT64_FORMAT",%u,%u)",
lock_name, sysid, tli, datid);
initStringInfo(&s);
LWLockAcquire(bdr_locks_ctl->lock, LW_EXCLUSIVE);
if (bdr_my_locks_database->lockcount == 0)
{
Relation rel;
Datum values[10];
bool nulls[10];
HeapTuple tup;
/*
* No previous DDL lock found. Start acquiring it.
*/
elog(ddl_lock_log_level(DDL_LOCK_TRACE_DEBUG),
LOCKTRACE "no prior global lock found, acquiring global lock locally");
/* Add a row to bdr_locks */
StartTransactionCommand();
memset(nulls, 0, sizeof(nulls));
rel = heap_open(BdrLocksRelid, RowExclusiveLock);
values[0] = CStringGetTextDatum(lock_name);
appendStringInfo(&s, UINT64_FORMAT, sysid);
values[1] = CStringGetTextDatum(s.data);
resetStringInfo(&s);
values[2] = ObjectIdGetDatum(tli);
values[3] = ObjectIdGetDatum(datid);
values[4] = TimestampTzGetDatum(GetCurrentTimestamp());
appendStringInfo(&s, UINT64_FORMAT, GetSystemIdentifier());