-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathbdr_locks.c
2484 lines (2082 loc) · 73.5 KB
/
bdr_locks.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
/* -------------------------------------------------------------------------
*
* 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. We don't have autonomous tx's or suspendable tx's
* so we can't do a tx while another is in progress. Instead the 'messaging'
* feature is used which allows to inject transactional and nontransactional
* messages in the changestream. (We could instead make an IPC request to
* another worker to do the required transaction, but since we have
* non-transactional messaging it's simpler to use it).
*
* 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.
*
* A global 'ddl' lock may be upgraded to the stronger 'write' lock. This
* carries no deadlock hazard because the weakest lock mode is still an
* exclusive lock.
*
* Note that DDL locking in 'write' mode flushes the queues of all edges in
* the node graph, not just those between the acquiring node and its peers.
* If node A requests the lock, then it must have fully replayed from B and
* C and vice versa. But B and C must also have fully replayed each others'
* outstanding replication queues. This ensures that no row changes that
* might conflict with the DDL can be in flight anywhere.
*
*
* DDL lock acquisition 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.
*
* (We could wait, but would need to internally release, back off, and
* retry, and we'd likely land up getting cancelled anyway so it's not
* worth it.)
*
* 2) It sends out a 'acquire_lock' message to all other nodes and sets
* local state BDR_LOCKSTATE_ACQUIRE_TALLYING_CONFIRMATIONS
*
*
* Now, on each other node:
*
* 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. Set lock
* state BDR_LOCKSTATE_PEER_BEGIN_CATCHUP.
*
* For 'write' mode locks:
*
* 5a) All concurrent user transactions will be cancelled (after a grace
* period, for 'write' mode locks only).
* State BDR_LOCKSTATE_PEER_CANCEL_XACTS.
*
* 5b) A 'request_replay_confirm' message will be sent to all other nodes
* containing a lsn that has to be replayed.
* State BDR_LOCKSTATE_PEER_CATCHUP
*
* 5c) When a 'request_replay_confirm' message is received, a
* 'replay_confirm' message will be sent back.
*
* 5d) Once all other nodes have replied with 'replay_confirm' the local DDL lock
* has been successfully acquired on the node reading the 'acquire_lock'
* message (from 3)).
*
* or for 'ddl' mode locks:
*
* 5) The replay confirmation process is skipped.
*
* then for both 'ddl' and 'write' mode locks:
*
* 6) The local bdr_global_locks entry will be updated to the 'acquired'
* state and a 'confirm_lock' message will be sent out indicating that
* the local ddl lock is fully acquired. Set lockstate
* BDR_LOCKSTATE_PEER_CONFIRMED.
*
*
* On the node requesting the global lock
* (state still BDR_LOCKSTATE_ACQUIRE_TALLYING_CONFIRMATIONS):
*
* 9) Apply workers receive confirm_lock and decline_lock messages and tally
* them in the local DB's BdrLocksDBState in shared memory.
*
* In the user backend that tried to get the lock:
*
* 10a) Once all nodes have replied with 'confirm_lock' messages the global
* ddl lock has been acquired. Set lock state
* BDR_LOCKSTATE_ACQUIRE_ACQUIRED. Wait for the xact to commit or
* abort.
*
* or
*
* 10b) If any 'decline_lock' message is received, the global lock acquisition
* has failed. Abort the acquiring transaction.
*
* 11) Send a release_lock message. Set lock state BDR_LOCKSTATE_NOLOCK
*
*
* on all peers:
*
* 12) When 'release_lock' is received, release local DDL lock and remove
* entry from global locks table. Ignore if not acquired. Set lock state
* BDR_LOCKSTATE_NOLOCK.
*
*
* There's some additional complications to handle crash safety:
*
* Everytime a node starts up (after crash or clean shutdown) it sends out a
* 'startup' message causing all other nodes to release locks held by it
* before shutdown/crash. Then the bdr_global_locks table is read. All
* existing local DDL locks held on behalf of other peers are acquired. If a
* lock still is in 'catchup' phase the local lock acquiration process is
* re-started at step 6)
*
* Because only one decline is sufficient to stop a DDL lock acquisition,
* it's likely that two concurrent attempts to acquire the DDL lock from
* different nodes will both fail as each declines the other's request, or
* one or more of their peers acquire locks in different orders. Apps that
* do DDL from multiple nodes must be prepared to retry DDL.
*
* DDL locks are transaction-level but do not respect subtransactions.
* They are not released if a subtransaction rolls back.
* (2ndQuadrant/bdr-private#77).
*
* IDENTIFICATION
* bdr_locks.c
*
* -------------------------------------------------------------------------
*/
#include "postgres.h"
#include "bdr.h"
#include "bdr_locks.h"
#include "bdr_messaging.h"
#include "fmgr.h"
#include "funcapi.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/message.h"
#include "replication/origin.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 "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/memutils.h"
#include "utils/pg_lsn.h"
#include "utils/rel.h"
#include "utils/guc.h"
#include "utils/snapmgr.h"
#include "pgstat.h"
#define LOCKTRACE "DDL LOCK TRACE: "
extern Datum bdr_ddl_lock_info(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(bdr_ddl_lock_info);
/* 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 enum BDRLockState {
BDR_LOCKSTATE_NOLOCK,
/* States on acquiring node */
BDR_LOCKSTATE_ACQUIRE_TALLY_CONFIRMATIONS,
BDR_LOCKSTATE_ACQUIRE_ACQUIRED,
/* States on peer nodes */
BDR_LOCKSTATE_PEER_BEGIN_CATCHUP,
BDR_LOCKSTATE_PEER_CANCEL_XACTS,
BDR_LOCKSTATE_PEER_CATCHUP,
BDR_LOCKSTATE_PEER_CONFIRMED
} BDRLockState;
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 */
int nnodes;
/* has startup progressed far enough to allow writes? */
bool locked_and_loaded;
/*
* despite the use of a lock counter, currently only one
* lock may exist at a time.
*/
int lockcount;
/*
* If the lock is held by a peer, the node ID of the peer.
* InvalidRepOriginId represents the local node, like usual.
* Lock may be in the process of being acquired not fully
* held.
*/
RepOriginId lock_holder;
/* pid of lock holder if it's a backend of on local node */
int lock_holder_local_pid;
/* Type of lock held or being acquired */
BDRLockType lock_type;
/*
* Progress of lock acquisition. We need this so that if we set lock_type
* then rollback a subxact, or if we start a lock upgrade, we know we're
* not in fully acquired state.
*/
BDRLockState lock_state;
/* 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 {
LWLockId lock;
BdrLocksDBState *dbstate;
BDRLockWaiter *waiters;
} BdrLocksCtl;
typedef struct BDRLockXactCallbackInfo {
/* Lock state to apply at commit time */
BDRLockState commit_pending_lock_state;
bool pending;
} BDRLockXactCallbackInfo;
static BDRLockXactCallbackInfo bdr_lock_state_xact_callback_info
= {BDR_LOCKSTATE_NOLOCK, false};
static void bdr_lock_holder_xact_callback(XactEvent event, void *arg);
static void bdr_lock_state_xact_callback(XactEvent event, void *arg);
static BdrLocksDBState * bdr_locks_find_database(Oid dbid, bool create);
static void bdr_locks_find_my_database(bool create);
static char *bdr_lock_state_to_name(BDRLockState lock_state);
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 void register_holder_xact_callback(void);
static void register_state_xact_callback(void);
static void bdr_locks_release_local_ddl_lock(const BDRNodeId * const lock);
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;
/* SQL function to explcitly acquire global DDL lock */
PGDLLIMPORT extern Datum bdr_acquire_global_lock_sql(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(bdr_acquire_global_lock_sql);
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 = &(GetNamedLWLockTranche("bdr_locks")->lock);
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());
RequestNamedLWLockTranche("bdr_locks", 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];
slist_iter iter;
waiter->proc = proc;
/*
* The waiter list shouldn't be huge, and compared to the expense of a DDL
* lock it's cheap to check if we're already registered. After all, we're
* just adding ourselves to a wait-notification list. slist has no guard
* against adding a cycle, and we'd infinite-loop in bdr_locks_on_unlock
* otherwise. See 2ndQuadrant/bdr-private#130.
*/
slist_foreach(iter, &bdr_my_locks_database->waiters)
{
if (iter.cur == &waiter->node)
{
elog(WARNING, LOCKTRACE "backend %d already registered as waiter for DDL lock release",
MyProcPid);
Assert(false); /* crash in debug builds */
return;
}
}
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);
/*
* Detect a self-referencing node and bail out by tossing the rest of
* the list. This shouldn't be necessary, it's an emergency bailout
* to stop us going into an infinite loop while holding a LWLock.
*
* We have to PANIC here so we force shmem and lwlock state to be
* re-inited. We could possibly just clobber the list and exit, leaving
* waiters dangling. But since this should be guarded against by
* bdr_locks_addwaiter, it shouldn't happen anyway.
* (See: 2ndQuadrant/bdr-private#130)
*/
if (slist_has_next(&bdr_my_locks_database->waiters, node)
&& slist_next_node(&bdr_my_locks_database->waiters, node) == node)
elog(PANIC, "cycle detected in DDL lock waiter linked list");
waiter = slist_container(BDRLockWaiter, node, node);
proc = waiter->proc;
SetLatch(&proc->procLatch);
}
}
/*
* Set up a new lock_state to be applied on commit. No prior pending state may
* be set.
*/
static void
bdr_locks_set_commit_pending_state(BDRLockState state)
{
register_state_xact_callback();
Assert(!bdr_lock_state_xact_callback_info.pending);
bdr_lock_state_xact_callback_info.commit_pending_lock_state = state;
bdr_lock_state_xact_callback_info.pending = true;
}
/*
* 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(void)
{
Relation rel;
ScanKey key;
SysScanDesc scan;
Snapshot snap;
HeapTuple tuple;
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 = -1;
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");
bdr_send_message(&s, false);
/*
* reacquire all old ddl locks (held by other nodes) in
* bdr.bdr_global_locks 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;
RepOriginId node_id;
BDRLockType lock_type;
BDRNodeId locker_id;
heap_deform_tuple(tuple, RelationGetDescr(rel),
values, isnull);
/* lookup the lock owner's node id */
if (isnull[9])
/*
* A bug in BDR prior to 2.0.4 could leave this null
* when it should really be in catchup mode.
*/
{
elog(WARNING, "fixing up bad DDL lock state, should be 'catchup' not NULL");
state = "catchup";
}
else
state = TextDatumGetCString(values[9]);
if (sscanf(TextDatumGetCString(values[1]), UINT64_FORMAT, &locker_id.sysid) != 1)
elog(ERROR, "could not parse sysid %s",
TextDatumGetCString(values[1]));
locker_id.timeline = DatumGetObjectId(values[2]);
locker_id.dboid = DatumGetObjectId(values[3]);
node_id = bdr_fetch_node_id_via_sysid(&locker_id);
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;
bdr_my_locks_database->lock_state = BDR_LOCKSTATE_PEER_CONFIRMED;
/* 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);
bdr_send_message(&s, false);
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->lock_state = BDR_LOCKSTATE_PEER_CATCHUP;
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;
}
/*
* Called from the perdb worker to update our idea of the number of nodes
* in the group, when we process an update from shmem.
*/
void
bdr_locks_set_nnodes(int nnodes)
{
Assert(IsBackgroundWorker);
Assert(bdr_my_locks_database != NULL);
Assert(nnodes >= 0);
LWLockAcquire(bdr_locks_ctl->lock, LW_EXCLUSIVE);
if (bdr_my_locks_database->nnodes < nnodes && bdr_my_locks_database->nnodes > 0 && !bdr_my_locks_database->lockcount)
{
/*
* Because we take the ddl lock before setting node_status = r now, and
* we only count ready nodes in the node count, it should only be
* possible for the node count to increase when the DDL lock is held.
*
* If there are older BDR nodes that don't take the DDL lock before
* joining this protection doesn't apply, so we can only warn about it.
* Unless there's a lock acquisition in progress (which we don't
* actually know from here) it's harmless anyway.
*
* A corresponding nodecount decrease without the DDL lock held is
* normal. Node part doesn't take the DDL lock, but it's careful
* to reject any in-progress DDL lock attempt or release any held
* lock.
*
* FIXME: there's a race here where we could release the lock before
* applying the final changes for the node in the perdb worker. We
* should really perform this test and update when we see the new
* bdr.bdr_nodes row arrive instead. See 2ndQuadrant/bdr-private#97.
*/
ereport(WARNING,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("number of nodes increased %d => %d while local DDL lock not held",
bdr_my_locks_database->nnodes, nnodes),
errhint("this should only happen during an upgrade from an older BDR version")));
}
bdr_my_locks_database->nnodes = nnodes;
LWLockRelease(bdr_locks_ctl->lock);
}
/*
* Handle a WAL message destined for bdr_locks.
*
* Note that we don't usually pq_getmsgend(), instead ignoring any trailing
* data. Future versions may add extra fields.
*/
bool
bdr_locks_process_message(int msg_type, bool transactional, XLogRecPtr lsn,
const BDRNodeId * const origin, StringInfo message)
{
bool handled = true;
Assert(CurrentMemoryContext == MessageContext);
if (msg_type == BDR_MESSAGE_START)
{
bdr_locks_process_remote_startup(origin);
}
else if (msg_type == BDR_MESSAGE_ACQUIRE_LOCK)
{
int lock_type;
if (message->cursor == message->len) /* Old proto */
lock_type = BDR_LOCK_WRITE;
else
lock_type = pq_getmsgint(message, 4);
bdr_process_acquire_ddl_lock(origin, lock_type);
}
else if (msg_type == BDR_MESSAGE_RELEASE_LOCK)
{
BDRNodeId peer;
/* locks are node-wide, so no node name */
bdr_getmsg_nodeid(message, &peer, false);
bdr_process_release_ddl_lock(origin, &peer);
}
else if (msg_type == BDR_MESSAGE_CONFIRM_LOCK)
{
BDRNodeId peer;
int lock_type;
/* locks are node-wide, so no node name */
bdr_getmsg_nodeid(message, &peer, false);
if (message->cursor == message->len) /* Old proto */
lock_type = BDR_LOCK_WRITE;
else
lock_type = pq_getmsgint(message, 4);
bdr_process_confirm_ddl_lock(origin, &peer, lock_type);
}
else if (msg_type == BDR_MESSAGE_DECLINE_LOCK)
{
BDRNodeId peer;
int lock_type;
/* locks are node-wide, so no node name */
bdr_getmsg_nodeid(message, &peer, false);
if (message->cursor == message->len) /* Old proto */
lock_type = BDR_LOCK_WRITE;
else
lock_type = pq_getmsgint(message, 4);
bdr_process_decline_ddl_lock(origin, &peer, lock_type);
}
else if (msg_type == BDR_MESSAGE_REQUEST_REPLAY_CONFIRM)
{
XLogRecPtr confirm_lsn;
confirm_lsn = pq_getmsgint64(message);
bdr_process_request_replay_confirm(origin, confirm_lsn);
}
else if (msg_type == BDR_MESSAGE_REPLAY_CONFIRM)
{
XLogRecPtr confirm_lsn;
confirm_lsn = pq_getmsgint64(message);
bdr_process_replay_confirm(origin, confirm_lsn);
}
else
{
elog(LOG, "unknown message type %d", msg_type);
handled = false;
}
Assert(CurrentMemoryContext == MessageContext);
return handled;
}
/*
* Callback to release the global lock on commit/abort of the holding xact.
* Only called from a user backend - or a bgworker from some unrelated tool.
*/
static void
bdr_lock_holder_xact_callback(XactEvent event, void *arg)
{
BDRNodeId myid;
Assert(arg == NULL);
Assert(!IsBdrApplyWorker());
bdr_make_my_nodeid(&myid);
if (!this_xact_acquired_lock)
return;
if (event == XACT_EVENT_ABORT || event == XACT_EVENT_COMMIT)
{
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 */
bdr_send_nodeid(&s, &myid, false);
bdr_send_message(&s, false);
LWLockAcquire(bdr_locks_ctl->lock, LW_EXCLUSIVE);
if (bdr_my_locks_database->lockcount > 0)
{
Assert(bdr_my_locks_database->lock_state > BDR_LOCKSTATE_NOLOCK);
bdr_my_locks_database->lockcount--;
}
else
elog(WARNING, "Releasing unacquired global lock");
this_xact_acquired_lock = false;
Assert(bdr_my_locks_database->lock_holder_local_pid == MyProcPid);
bdr_my_locks_database->lock_holder_local_pid = 0;
bdr_my_locks_database->lock_type = BDR_LOCK_NOLOCK;
bdr_my_locks_database->lock_state = BDR_LOCKSTATE_NOLOCK;
bdr_my_locks_database->replay_confirmed = 0;
bdr_my_locks_database->replay_confirmed_lsn = InvalidXLogRecPtr;
bdr_my_locks_database->requestor = NULL;
/* We requested the lock we're releasing */
if (bdr_my_locks_database->lockcount == 0)
bdr_locks_on_unlock();
LWLockRelease(bdr_locks_ctl->lock);
}
}
static void
register_holder_xact_callback(void)
{
static bool registered;
if (!registered)
{
RegisterXactCallback(bdr_lock_holder_xact_callback, NULL);
registered = true;
}
}
/*
* Callback to update shmem state after we change global ddl lock state in
* bdr_global_locks. Only called from apply worker and perdb worker.
*/
static void
bdr_lock_state_xact_callback(XactEvent event, void *arg)
{
Assert(arg == NULL);
Assert(IsBackgroundWorker);
Assert(IsBdrApplyWorker()||IsBdrPerdbWorker());
if (event == XACT_EVENT_COMMIT && bdr_lock_state_xact_callback_info.pending)
{
Assert(LWLockHeldByMe((bdr_locks_ctl->lock)));
bdr_my_locks_database->lock_state
= bdr_lock_state_xact_callback_info.commit_pending_lock_state;
bdr_lock_state_xact_callback_info.pending = false;
}
}
static void
register_state_xact_callback(void)
{
static bool registered;
if (!registered)
{
RegisterXactCallback(bdr_lock_state_xact_callback, NULL);
registered = true;
}
}
static SysScanDesc
locks_begin_scan(Relation rel, Snapshot snap, const BDRNodeId * const node)
{
ScanKey key;
char buf[30];
key = (ScanKey) palloc(sizeof(ScanKeyData) * 4);
sprintf(buf, UINT64_FORMAT, node->sysid);
ScanKeyInit(&key[0],
2,
BTEqualStrategyNumber, F_TEXTEQ,
CStringGetTextDatum(buf));
ScanKeyInit(&key[1],
3,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(node->timeline));
ScanKeyInit(&key[2],
4,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(node->dboid));
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)
{
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);
/* shouldn't be called with ddl locking disabled */
Assert(!bdr_skip_ddl_locking);
bdr_locks_find_my_database(false);
/*
* Currently we only support one lock. We might be called with it already
* held or to upgrade it.
*/
Assert((bdr_my_locks_database->lock_type == BDR_LOCK_NOLOCK && bdr_my_locks_database->lockcount == 0 && !this_xact_acquired_lock)
|| (bdr_my_locks_database->lock_type > BDR_LOCK_NOLOCK && bdr_my_locks_database->lockcount == 1));
/* No need to do anything if already holding requested lock. */
if (this_xact_acquired_lock &&
bdr_my_locks_database->lock_type >= lock_type)
{
Assert(bdr_my_locks_database->lock_holder_local_pid == MyProcPid);
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 "acquiring in mode <%s> (upgrading from <%s>) from <%d> peer nodes for "BDR_NODEID_FORMAT_WITHNAME" [tracelevel=%s]",
bdr_lock_type_to_name(lock_type),