forked from keenser/bdr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbdr_apply.c
2955 lines (2492 loc) · 79.6 KB
/
bdr_apply.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_apply.c
* Replication!!!
*
* Replication???
*
* Copyright (C) 2012-2015, PostgreSQL Global Development Group
*
* IDENTIFICATION
* bdr_apply.c
*
* -------------------------------------------------------------------------
*/
#include "postgres.h"
#include "bdr.h"
#include "bdr_locks.h"
#include "bdr_messaging.h"
#include "funcapi.h"
#include "libpq-fe.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "access/commit_ts.h"
#include "access/htup_details.h"
#include "access/relscan.h"
#include "access/xact.h"
#include "catalog/catversion.h"
#include "catalog/dependency.h"
#include "catalog/index.h"
#include "catalog/namespace.h"
#include "catalog/objectaddress.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
#include "executor/spi.h"
#include "libpq/pqformat.h"
#include "mb/pg_wchar.h"
#include "parser/parse_type.h"
#include "replication/logical.h"
#include "replication/origin.h"
#include "storage/ipc.h"
#include "storage/lmgr.h"
#include "storage/lwlock.h"
#include "storage/proc.h"
#include "tcop/pquery.h"
#include "tcop/tcopprot.h"
#include "tcop/utility.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/datetime.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
/* Useful for development:
#define VERBOSE_INSERT
#define VERBOSE_DELETE
#define VERBOSE_UPDATE
*/
/* Relation oid cache; initialized then left unchanged */
Oid QueuedDDLCommandsRelid = InvalidOid;
Oid QueuedDropsRelid = InvalidOid;
/* Global apply worker state */
BDRNodeId origin;
bool started_transaction = false;
/* During apply, holds xid of remote transaction */
TransactionId replication_origin_xid = InvalidTransactionId;
/*
* For tracking of the remote origin's information when in catchup mode
* (BDR_OUTPUT_TRANSACTION_HAS_ORIGIN).
*/
static BDRNodeId remote_origin;
static XLogRecPtr remote_origin_lsn = InvalidXLogRecPtr;
/* The local identifier for the remote's origin, if any. */
static RepOriginId remote_origin_id = InvalidRepOriginId;
/*
* A message counter for the xact, for debugging. We don't send
* the remote change LSN with messages, so this aids identification
* of which change causes an error.
*/
static uint32 xact_action_counter;
/*
* This code only runs within an apply bgworker, so we can stash a pointer to our
* state in shm in a global for convenient access.
*/
static BdrApplyWorker *bdr_apply_worker = NULL;
static BdrConnectionConfig *bdr_apply_config = NULL;
dlist_head bdr_lsn_association = DLIST_STATIC_INIT(bdr_lsn_association);
struct ActionErrCallbackArg
{
const char * action_name;
const char * remote_nspname;
const char * remote_relname;
bool is_ddl_or_drop;
bool suppress_output;
};
static BDRRelation *read_rel(StringInfo s, LOCKMODE mode, struct ActionErrCallbackArg *cbarg);
static void read_tuple_parts(StringInfo s, BDRRelation *rel, BDRTupleData *tup);
static void check_apply_update(BdrConflictType conflict_type,
RepOriginId local_node_id, TimestampTz local_ts,
BDRRelation *rel, HeapTuple local_tuple,
HeapTuple remote_tuple, HeapTuple *new_tuple,
bool *perform_update, bool *log_update,
BdrConflictResolution *resolution);
static void check_bdr_wakeups(BDRRelation *rel);
static HeapTuple process_queued_drop(HeapTuple cmdtup);
static void process_queued_ddl_command(HeapTuple cmdtup, bool tx_just_started);
static bool bdr_performing_work(void);
static void process_remote_begin(StringInfo s);
static void process_remote_commit(StringInfo s);
static void process_remote_insert(StringInfo s);
static void process_remote_update(StringInfo s);
static void process_remote_delete(StringInfo s);
static void get_local_tuple_origin(HeapTuple tuple,
TimestampTz *commit_ts,
RepOriginId *node_id);
static void abs_timestamp_difference(TimestampTz start_time,
TimestampTz stop_time,
long *secs, int *microsecs);
#if defined(VERBOSE_INSERT) || defined(VERBOSE_UPDATE) || defined(VERBOSE_DELETE)
static void log_tuple(const char *format, TupleDesc desc, HeapTuple tup);
#endif
static void
format_action_description(
StringInfo si,
const char * action_name,
const char * remote_nspname,
const char * remote_relname,
bool is_ddl_or_drop)
{
appendStringInfoString(si, "apply ");
appendStringInfoString(si, action_name);
if (remote_nspname != NULL
&& remote_relname != NULL
&& !is_ddl_or_drop)
{
appendStringInfo(si, " from remote relation %s.%s",
remote_nspname, remote_relname);
}
appendStringInfo(si,
" in commit before %X/%X, xid %u commited at %s (action #%u)",
(uint32)(replorigin_session_origin_lsn>>32),
(uint32)replorigin_session_origin_lsn,
replication_origin_xid,
timestamptz_to_str(replorigin_session_origin_timestamp),
xact_action_counter);
if (replorigin_session_origin != InvalidRepOriginId)
{
appendStringInfo(si, " from node "BDR_NODEID_FORMAT_WITHNAME,
BDR_NODEID_FORMAT_WITHNAME_ARGS(origin));
}
if (remote_origin_id != InvalidRepOriginId)
{
appendStringInfo(si, " forwarded from commit %X/%X on node "BDR_NODEID_FORMAT_WITHNAME,
(uint32)(remote_origin_lsn>>32),
(uint32)remote_origin_lsn,
BDR_NODEID_FORMAT_WITHNAME_ARGS(remote_origin));
}
}
static void
action_error_callback(void *arg)
{
struct ActionErrCallbackArg *action = (struct ActionErrCallbackArg*)arg;
StringInfoData si;
if (!action->suppress_output)
{
initStringInfo(&si);
format_action_description(&si,
action->action_name,
action->remote_nspname,
action->remote_relname,
action->is_ddl_or_drop);
errcontext("%s", si.data);
}
}
static void
process_remote_begin(StringInfo s)
{
XLogRecPtr commit_afterend_lsn;
TimestampTz committime;
TransactionId remote_xid;
char statbuf[100];
int apply_delay = bdr_apply_config->apply_delay;
int flags = 0;
ErrorContextCallback errcallback;
struct ActionErrCallbackArg cbarg;
Assert(bdr_apply_worker != NULL);
xact_action_counter = 1;
memset(&cbarg, 0, sizeof(struct ActionErrCallbackArg));
cbarg.action_name = "BEGIN";
errcallback.callback = action_error_callback;
errcallback.arg = &cbarg;
errcallback.previous = error_context_stack;
error_context_stack = &errcallback;
started_transaction = false;
remote_origin_id = InvalidRepOriginId;
flags = pq_getmsgint(s, 4);
/*
* This is the LSN of the end of the commit xlog record + 1, even
* though we're in BEGIN. We have it because we process the whole
* reorder buffer only at commit time.
*/
commit_afterend_lsn = pq_getmsgint64(s);
Assert(commit_afterend_lsn != InvalidXLogRecPtr);
committime = pq_getmsgint64(s);
remote_xid = pq_getmsgint(s, 4);
if (flags & BDR_OUTPUT_TRANSACTION_HAS_ORIGIN)
{
bdr_getmsg_nodeid(s, &remote_origin, false);
remote_origin_lsn = pq_getmsgint64(s);
}
else
{
/* Transaction originated directly from remote node */
remote_origin.sysid = 0;
remote_origin.timeline = 0;
remote_origin.dboid = InvalidOid;
remote_origin_lsn = InvalidXLogRecPtr;
}
/*
* Set up state for commit and conflict detection. The timestamp will be
* recorded as the replicated xact's commit timestamp, and the LSN will be
* used to advance the replication origin for the node at local COMMIT
* time. Set the remote LSN to the end of the remote commit record + 1
* so we know exactly when the next record to start processing is.
*
* This means that replorigin_session_origin_lsn and our replication
* origin doesn't actually point to the last-processed commit record,
* but just after it.
*/
replorigin_session_origin_lsn = commit_afterend_lsn;
replorigin_session_origin_timestamp = committime;
/* store remote xid for logging and debugging */
replication_origin_xid = remote_xid;
snprintf(statbuf, sizeof(statbuf),
"bdr_apply: BEGIN origin(orig_lsn, timestamp): %X/%X, %s",
(uint32) (replorigin_session_origin_lsn >> 32),
(uint32) replorigin_session_origin_lsn,
timestamptz_to_str(committime));
pgstat_report_activity(STATE_RUNNING, statbuf);
if (apply_delay == -1)
apply_delay = bdr_default_apply_delay;
/*
* If we're in catchup mode, see if this transaction is relayed from
* elsewhere and prepare to advance the appropriate replication origin.
*/
if (flags & BDR_OUTPUT_TRANSACTION_HAS_ORIGIN)
{
char remote_ident[256];
NameData replication_name;
MemoryContext old_ctx;
BDRNodeId my_nodeid;
bdr_make_my_nodeid(&my_nodeid);
if (bdr_nodeid_eq(&remote_origin, &my_nodeid))
{
/*
* This might not have to be an error condition, but we don't cope
* with it for now and it shouldn't arise for use of catchup mode
* for init_replica.
*/
ereport(ERROR,
(errmsg("Replication loop in catchup mode"),
errdetail("Received a transaction from the remote node that originated on this node")));
}
/* replication_name is currently unused in bdr */
NameStr(replication_name)[0] = '\0';
/*
* To determine whether the commit was forwarded by the upstream from
* another node, we need to get the local RepOriginId for that node based
* on the (sysid, timelineid, dboid) supplied in catchup mode.
*/
snprintf(remote_ident, sizeof(remote_ident),
BDR_REPORIGIN_ID_FORMAT,
remote_origin.sysid, remote_origin.timeline, remote_origin.dboid, MyDatabaseId,
NameStr(replication_name));
old_ctx = CurrentMemoryContext;
StartTransactionCommand();
remote_origin_id = replorigin_by_name(remote_ident, false);
CommitTransactionCommand();
(void) MemoryContextSwitchTo(old_ctx);
}
if (bdr_trace_replay)
{
StringInfoData si;
initStringInfo(&si);
format_action_description(&si, "BEGIN", NULL, NULL, false);
cbarg.suppress_output = true;
elog(LOG, "TRACE: %s", si.data);
cbarg.suppress_output = false;
pfree(si.data);
}
/* don't want the overhead otherwise */
if (apply_delay > 0)
{
/* loop in case we're woken early in a sleep by an interrupt */
while (true)
{
long sec;
int usec;
int ret;
long delay_ms;
TimestampTz current;
current = GetCurrentTimestamp();
/*
* Some amount of clock drift/skew is normal, so
* we must handle remote commits that are in the future
* according to our local clock.
*/
if (current < replorigin_session_origin_timestamp)
{
TimestampDifference(replorigin_session_origin_timestamp, current,
&sec, &usec);
/* ignore small skews */
if (sec > 1)
ereport(WARNING,
(errmsg("clock skew detected: node "BDR_NODEID_FORMAT_WITHNAME" clock is ahead of local clock by at least %ld.%03d seconds",
BDR_NODEID_FORMAT_WITHNAME_ARGS(origin), sec,
usec / 1000)));
/*
* Now clamp the delay to max apply delay. If we're woken
* mid-sleep this could mean we repeat the warning and wait
* longer than apply_delay but ... don't have your clocks
* ahead, then!
*/
delay_ms = apply_delay;
}
else
{
current = TimestampTzPlusMilliseconds(current,
-apply_delay);
TimestampDifference(current, replorigin_session_origin_timestamp,
&sec, &usec);
/*
* WaitLatch doesn't support > INT_MAX ms, including any us component,
* and we have to guard against overflow anyway.
*/
if (sec >= (INT_MAX/1000 - 1000))
{
elog(WARNING, "ignoring absurd remote commit timestamp and/or apply_delay");
delay_ms = 0;
}
else
delay_ms = sec * 1000 + usec / 1000L;
/* TimestampDifference returns 0 if start >= end, so: */
if (delay_ms == 0)
break;
}
ret = WaitLatch(&MyProc->procLatch,
WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
delay_ms, PG_WAIT_EXTENSION);
if (ret & WL_POSTMASTER_DEATH)
proc_exit(1);
ResetLatch(&MyProc->procLatch);
CHECK_FOR_INTERRUPTS();
}
}
if (error_context_stack == &errcallback)
error_context_stack = errcallback.previous;
}
/*
* Process a commit message from the output plugin, advance replication
* identifiers, commit the local transaction, and determine whether replay
* should continue.
*
* Returns true if apply should continue with the next record, false if replay
* should stop after this record.
*/
static void
process_remote_commit(StringInfo s)
{
XLogRecPtr commit_lsn PG_USED_FOR_ASSERTS_ONLY;
TimestampTz committime PG_USED_FOR_ASSERTS_ONLY;
TimestampTz commit_afterend_lsn;
int flags;
ErrorContextCallback errcallback;
struct ActionErrCallbackArg cbarg;
Assert(bdr_apply_worker != NULL);
xact_action_counter++;
memset(&cbarg, 0, sizeof(struct ActionErrCallbackArg));
cbarg.action_name = "COMMIT";
errcallback.callback = action_error_callback;
errcallback.arg = &cbarg;
errcallback.previous = error_context_stack;
error_context_stack = &errcallback;
flags = pq_getmsgint(s, 4);
if (flags != 0)
elog(ERROR, "Commit flags are currently unused, but flags was set to %i", flags);
/* order of access to fields after flags is important */
commit_lsn = pq_getmsgint64(s); /* start of commit record; not used anymore */
commit_afterend_lsn = pq_getmsgint64(s); /* end of commit record + 1 */
committime = pq_getmsgint64(s);
if (bdr_trace_replay)
{
StringInfoData si;
initStringInfo(&si);
format_action_description(&si, "COMMIT", NULL, NULL, false);
cbarg.suppress_output = true;
elog(LOG, "TRACE: %s", si.data);
cbarg.suppress_output = false;
pfree(si.data);
}
Assert(committime == replorigin_session_origin_timestamp);
Assert(replorigin_session_origin_lsn == commit_afterend_lsn /* bdr 2.0 msg */
|| replorigin_session_origin_lsn == commit_lsn); /* bdr 1.0 msg */
/*
* BDR 1.0 used to send the start-of-commit lsn (commit_lsn) in BEGIN,
* not the position of the end of the commit record, and we might have
* used that in the replorigin settings if that's all we had.
*
* That's wrong; we're supposed to use end-of-commit + 1. But with BDR
* 1.0 we don't have that information. To protect against replaying
* the same commit again, report that we've flushed at least 1 byte
* past start-of-commit.
*/
if (replorigin_session_origin_lsn == commit_lsn)
replorigin_session_origin_lsn += 1;
if (started_transaction)
{
BdrFlushPosition *flushpos;
CommitTransactionCommand();
(void) MemoryContextSwitchTo(MessageContext);
/*
* Associate the end of the remote commit lsn with the local end of
* the commit record.
*/
flushpos = (BdrFlushPosition *)
MemoryContextAlloc(TopMemoryContext, sizeof(BdrFlushPosition));
flushpos->local_end = XactLastCommitEnd;
/* Feedback is supposed to be the last flushed LSN + 1 */
flushpos->remote_end = replorigin_session_origin_lsn;
dlist_push_tail(&bdr_lsn_association, &flushpos->node);
/* report stats, only relevant if something was actually written */
pgstat_report_stat(false);
}
pgstat_report_activity(STATE_IDLE, NULL);
/*
* We set the session origin flush point up as
* replorigin_session_origin_lsn in process_remote_begin, so no further
* action is required here. XactLogCommitRecord(...) will write out the
* replorigin_session_origin_lsn and advance our session's replication
* origin in-memory state accordingly.
*
* However, if we're in catchup mode, see if the commit is relayed from
* elsewhere and advance the replication origin corresponding to the
* appropriate node, since that won't get advanced automatically
* on commit.
*/
if (remote_origin_id != InvalidRepOriginId &&
remote_origin_id != replorigin_session_origin)
{
/*
* The row isn't from the immediate upstream; advance the slot of the
* node it originally came from so we start replay of that node's
* change data at the right place.
*/
replorigin_advance(remote_origin_id, remote_origin_lsn,
XactLastCommitEnd, false, true);
}
CurrentResourceOwner = bdr_saved_resowner;
bdr_count_commit();
replication_origin_xid = InvalidTransactionId;
replorigin_session_origin_lsn = InvalidXLogRecPtr;
replorigin_session_origin_timestamp = 0;
xact_action_counter = 0;
/*
* Stop replay if we're doing limited replay and we've replayed up to the
* last record we're supposed to process. Since the end lsn points to the
* start of the next record, we should stop if replay equals it.
*/
if (bdr_apply_worker->replay_stop_lsn != InvalidXLogRecPtr
&& bdr_apply_worker->replay_stop_lsn <= commit_afterend_lsn)
{
ereport(LOG,
(errmsg("bdr apply finished processing; replayed up to %X/%X of required %X/%X",
(uint32)(commit_afterend_lsn>>32), (uint32)commit_afterend_lsn,
(uint32)(bdr_apply_worker->replay_stop_lsn>>32), (uint32)bdr_apply_worker->replay_stop_lsn)));
/*
* We clear the replay_stop_lsn field to indicate successful catchup,
* so we don't need a separate flag field in shmem for all apply
* workers.
*/
bdr_apply_worker->replay_stop_lsn = InvalidXLogRecPtr;
/* flush all writes so the latest position can be reported back to the sender */
XLogFlush(GetXLogWriteRecPtr());
/* Stop gracefully */
proc_exit(0);
}
if (error_context_stack == &errcallback)
error_context_stack = errcallback.previous;
}
static void
process_remote_insert(StringInfo s)
{
char action;
EState *estate;
BDRTupleData new_tuple;
TupleTableSlot *newslot;
TupleTableSlot *oldslot;
BDRRelation *rel;
bool started_tx;
ResultRelInfo *relinfo;
ItemPointer conflicts;
bool conflict = false;
ScanKey *index_keys;
int i;
ItemPointerData conflicting_tid;
ErrorContextCallback errcallback;
struct ActionErrCallbackArg cbarg;
ItemPointerSetInvalid(&conflicting_tid);
xact_action_counter++;
memset(&cbarg, 0, sizeof(struct ActionErrCallbackArg));
cbarg.action_name = "INSERT";
errcallback.callback = action_error_callback;
errcallback.arg = &cbarg;
errcallback.previous = error_context_stack;
error_context_stack = &errcallback;
started_tx = bdr_performing_work();
Assert(bdr_apply_worker != NULL);
rel = read_rel(s, RowExclusiveLock, &cbarg);
if (bdr_trace_replay)
{
StringInfoData si;
initStringInfo(&si);
format_action_description(&si, "INSERT",
cbarg.remote_nspname, cbarg.remote_relname, false);
cbarg.suppress_output = true;
elog(LOG, "TRACE: %s", si.data);
cbarg.suppress_output = false;
pfree(si.data);
}
action = pq_getmsgbyte(s);
if (action != 'N')
elog(ERROR, "expected new tuple but got %d",
action);
estate = bdr_create_rel_estate(rel->rel);
newslot = ExecInitExtraTupleSlot(estate, NULL);
oldslot = ExecInitExtraTupleSlot(estate, NULL);
ExecSetSlotDescriptor(newslot, RelationGetDescr(rel->rel));
ExecSetSlotDescriptor(oldslot, RelationGetDescr(rel->rel));
read_tuple_parts(s, rel, &new_tuple);
{
HeapTuple tup;
tup = heap_form_tuple(RelationGetDescr(rel->rel),
new_tuple.values, new_tuple.isnull);
ExecStoreTuple(tup, newslot, InvalidBuffer, true);
}
if (rel->rel->rd_rel->relkind != RELKIND_RELATION)
elog(ERROR, "unexpected relkind '%c' rel \"%s\"",
rel->rel->rd_rel->relkind, RelationGetRelationName(rel->rel));
/* debug output */
#ifdef VERBOSE_INSERT
log_tuple("INSERT:%s", RelationGetDescr(rel->rel), newslot->tts_tuple);
#endif
/*
* Search for conflicting tuples.
*/
ExecOpenIndices(estate->es_result_relation_info, false);
relinfo = estate->es_result_relation_info;
index_keys = palloc0(relinfo->ri_NumIndices * sizeof(ScanKeyData*));
conflicts = palloc0(relinfo->ri_NumIndices * sizeof(ItemPointerData));
build_index_scan_keys(estate, index_keys, &new_tuple);
/* do a SnapshotDirty search for conflicting tuples */
for (i = 0; i < relinfo->ri_NumIndices; i++)
{
IndexInfo *ii = relinfo->ri_IndexRelationInfo[i];
bool found = false;
/*
* Only unique indexes are of interest here, and we can't deal with
* expression indexes so far. FIXME: predicates should be handled
* better.
*
* NB: Needs to match expression in build_index_scan_key
*/
if (!ii->ii_Unique || ii->ii_Expressions != NIL)
continue;
if (index_keys[i] == NULL)
continue;
Assert(ii->ii_Expressions == NIL);
/* if conflict: wait */
found = find_pkey_tuple(index_keys[i],
rel, relinfo->ri_IndexRelationDescs[i],
oldslot, true, LockTupleExclusive);
/* alert if there's more than one conflicting unique key */
if (found &&
ItemPointerIsValid(&conflicting_tid) &&
!ItemPointerEquals(&oldslot->tts_tuple->t_self,
&conflicting_tid))
{
/* TODO: Report tuple identity in log */
ereport(ERROR,
(errcode(ERRCODE_UNIQUE_VIOLATION),
errmsg("multiple unique constraints violated by remotely INSERTed tuple"),
errdetail("Cannot apply transaction because remotely INSERTed tuple "
"conflicts with a local tuple on more than one UNIQUE "
"constraint and/or PRIMARY KEY"),
errhint("Resolve the conflict by removing or changing the conflicting "
"local tuple")));
}
else if (found)
{
ItemPointerCopy(&oldslot->tts_tuple->t_self, &conflicting_tid);
conflict = true;
break;
}
else
ItemPointerSetInvalid(&conflicts[i]);
CHECK_FOR_INTERRUPTS();
}
PushActiveSnapshot(GetTransactionSnapshot());
/*
* If there's a conflict use the version created later, otherwise do a
* plain insert.
*/
if (conflict)
{
TimestampTz local_ts;
RepOriginId local_node_id;
bool apply_update;
bool log_update;
HeapTuple user_tuple = NULL;
BdrApplyConflict *apply_conflict = NULL; /* Mute compiler */
BdrConflictResolution resolution;
get_local_tuple_origin(oldslot->tts_tuple, &local_ts, &local_node_id);
/*
* Use conflict triggers and/or last-update-wins to decide which tuple
* to retain.
*/
check_apply_update(BdrConflictType_InsertInsert,
local_node_id, local_ts, rel,
oldslot->tts_tuple, newslot->tts_tuple, &user_tuple,
&apply_update, &log_update, &resolution);
/*
* Log conflict to server log.
*/
if (log_update)
{
apply_conflict = bdr_make_apply_conflict(
BdrConflictType_InsertInsert, resolution,
replication_origin_xid, rel, oldslot, local_node_id,
newslot, local_ts, NULL /*no error*/);
bdr_conflict_log_serverlog(apply_conflict);
bdr_count_insert_conflict();
}
/*
* Finally, apply the update.
*/
if (apply_update)
{
/*
* User specified conflict handler provided a new tuple; form it to
* a bdr tuple.
*/
if (user_tuple)
{
#ifdef VERBOSE_INSERT
log_tuple("USER tuple:%s", RelationGetDescr(rel->rel), user_tuple);
#endif
ExecStoreTuple(user_tuple, newslot, InvalidBuffer, true);
}
simple_heap_update(rel->rel,
&oldslot->tts_tuple->t_self,
newslot->tts_tuple);
/* races will be resolved by abort/retry */
UserTableUpdateOpenIndexes(estate, newslot);
bdr_count_insert();
}
/* Log conflict to table */
if (log_update)
{
bdr_conflict_log_table(apply_conflict);
bdr_conflict_logging_cleanup();
}
}
else
{
simple_heap_insert(rel->rel, newslot->tts_tuple);
UserTableUpdateOpenIndexes(estate, newslot);
bdr_count_insert();
}
PopActiveSnapshot();
ExecCloseIndices(estate->es_result_relation_info);
check_bdr_wakeups(rel);
/* execute DDL if insertion was into the ddl command queue */
if (RelationGetRelid(rel->rel) == QueuedDDLCommandsRelid ||
RelationGetRelid(rel->rel) == QueuedDropsRelid)
{
HeapTuple ht;
LockRelId lockid = rel->rel->rd_lockInfo.lockRelId;
TransactionId oldxid = GetTopTransactionId();
Oid relid = RelationGetRelid(rel->rel);
Relation qrel;
/* there never should be conflicts on these */
Assert(!conflict);
cbarg.is_ddl_or_drop = true;
/*
* Release transaction bound resources for CONCURRENTLY support.
*/
MemoryContextSwitchTo(MessageContext);
ht = heap_copytuple(newslot->tts_tuple);
LockRelationIdForSession(&lockid, RowExclusiveLock);
bdr_heap_close(rel, NoLock);
ExecResetTupleTable(estate->es_tupleTable, true);
FreeExecutorState(estate);
if (relid == QueuedDDLCommandsRelid)
{
cbarg.action_name = "QUEUED_DDL";
process_queued_ddl_command(ht, started_tx);
}
if (relid == QueuedDropsRelid)
{
cbarg.action_name = "QUEUED_DROP";
process_queued_drop(ht);
}
qrel = heap_open(QueuedDDLCommandsRelid, RowExclusiveLock);
UnlockRelationIdForSession(&lockid, RowExclusiveLock);
heap_close(qrel, NoLock);
if (oldxid != GetTopTransactionId())
{
CommitTransactionCommand();
(void) MemoryContextSwitchTo(MessageContext);
started_transaction = false;
}
}
else
{
bdr_heap_close(rel, NoLock);
ExecResetTupleTable(estate->es_tupleTable, true);
FreeExecutorState(estate);
}
CommandCounterIncrement();
if (error_context_stack == &errcallback)
error_context_stack = errcallback.previous;
}
static void
process_remote_update(StringInfo s)
{
char action;
EState *estate;
TupleTableSlot *newslot;
TupleTableSlot *oldslot;
bool pkey_sent;
bool found_tuple;
BDRTupleData old_tuple;
BDRTupleData new_tuple;
Oid idxoid;
BDRRelation *rel;
Relation idxrel;
ScanKeyData skey[INDEX_MAX_KEYS];
HeapTuple user_tuple = NULL,
remote_tuple = NULL;
ErrorContextCallback errcallback;
struct ActionErrCallbackArg cbarg;
xact_action_counter++;
memset(&cbarg, 0, sizeof(struct ActionErrCallbackArg));
cbarg.action_name = "UPDATE";
errcallback.callback = action_error_callback;
errcallback.arg = &cbarg;
errcallback.previous = error_context_stack;
error_context_stack = &errcallback;
bdr_performing_work();
rel = read_rel(s, RowExclusiveLock, &cbarg);
if (bdr_trace_replay)
{
StringInfoData si;
initStringInfo(&si);
format_action_description(&si, "UPDATE",
cbarg.remote_nspname, cbarg.remote_relname, false);
cbarg.suppress_output = true;
elog(LOG, "TRACE: %s", si.data);
cbarg.suppress_output = false;
pfree(si.data);
}
action = pq_getmsgbyte(s);
/* old key present, identifying key changed */
if (action != 'K' && action != 'N')
elog(ERROR, "expected action 'N' or 'K', got %c",
action);
estate = bdr_create_rel_estate(rel->rel);
oldslot = ExecInitExtraTupleSlot(estate, NULL);
ExecSetSlotDescriptor(oldslot, RelationGetDescr(rel->rel));
newslot = ExecInitExtraTupleSlot(estate, NULL);
ExecSetSlotDescriptor(newslot, RelationGetDescr(rel->rel));
if (action == 'K')
{
pkey_sent = true;
read_tuple_parts(s, rel, &old_tuple);
action = pq_getmsgbyte(s);
}
else
pkey_sent = false;
/* check for new tuple */
if (action != 'N')
elog(ERROR, "expected action 'N', got %c",
action);
if (rel->rel->rd_rel->relkind != RELKIND_RELATION)
elog(ERROR, "unexpected relkind '%c' rel \"%s\"",
rel->rel->rd_rel->relkind, RelationGetRelationName(rel->rel));
/* read new tuple */
read_tuple_parts(s, rel, &new_tuple);
/* lookup index to build scankey */
if (rel->rel->rd_indexvalid == 0)
RelationGetIndexList(rel->rel);
idxoid = rel->rel->rd_replidindex;
if (!OidIsValid(idxoid))
{
elog(ERROR, "could not find primary key for table with oid %u",
RelationGetRelid(rel->rel));
return;
}
/* open index, so we can build scan key for row */
idxrel = index_open(idxoid, RowExclusiveLock);
Assert(idxrel->rd_index->indisunique);
/* Use columns from the new tuple if the key didn't change. */
build_index_scan_key(skey, rel->rel, idxrel,
pkey_sent ? &old_tuple : &new_tuple);
PushActiveSnapshot(GetTransactionSnapshot());
/* look for tuple identified by the (old) primary key */
found_tuple = find_pkey_tuple(skey, rel, idxrel, oldslot, true,
pkey_sent ? LockTupleExclusive : LockTupleNoKeyExclusive);
if (found_tuple)
{
TimestampTz local_ts;
RepOriginId local_node_id;
bool apply_update;
bool log_update;
BdrApplyConflict *apply_conflict = NULL; /* Mute compiler */
BdrConflictResolution resolution;
remote_tuple = heap_modify_tuple(oldslot->tts_tuple,
RelationGetDescr(rel->rel),
new_tuple.values,
new_tuple.isnull,
new_tuple.changed);
ExecStoreTuple(remote_tuple, newslot, InvalidBuffer, true);
#ifdef VERBOSE_UPDATE
{
StringInfoData o;
initStringInfo(&o);
tuple_to_stringinfo(&o, RelationGetDescr(rel->rel), oldslot->tts_tuple);