-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathspock_apply.c
2877 lines (2427 loc) · 73.5 KB
/
spock_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
/*-------------------------------------------------------------------------
*
* spock_apply.c
* spock apply logic
*
* Copyright (c) 2022-2024, pgEdge, Inc.
* Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, The Regents of the University of California
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "miscadmin.h"
#include "libpq-fe.h"
#include "pgstat.h"
#include "access/htup_details.h"
#include "access/xact.h"
#include "catalog/namespace.h"
#include "catalog/pg_inherits.h"
#include "catalog/catalog.h"
#include "commands/async.h"
#include "commands/dbcommands.h"
#include "commands/sequence.h"
#include "commands/tablecmds.h"
#include "executor/executor.h"
#include "libpq/pqformat.h"
#include "mb/pg_wchar.h"
#include "nodes/makefuncs.h"
#include "nodes/parsenodes.h"
#include "optimizer/planner.h"
#ifdef XCP
#include "pgxc/pgxcnode.h"
#endif
#include "postmaster/interrupt.h"
#include "replication/origin.h"
#include "replication/reorderbuffer.h"
#include "replication/walsender.h"
#include "rewrite/rewriteHandler.h"
#include "storage/ipc.h"
#include "storage/lmgr.h"
#include "storage/proc.h"
#include "tcop/pquery.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#if PG_VERSION_NUM < 150000
#include "utils/int8.h"
#else
#include "utils/builtins.h"
#endif
#include "utils/acl.h"
#include "utils/jsonb.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/pg_lsn.h"
#include "utils/snapmgr.h"
#include "spock_common.h"
#include "spock_conflict.h"
#include "spock_executor.h"
#include "spock_node.h"
#include "spock_queue.h"
#include "spock_relcache.h"
#include "spock_repset.h"
#include "spock_rpc.h"
#include "spock_sync.h"
#include "spock_worker.h"
#include "spock_apply.h"
#include "spock_apply_heap.h"
#include "spock_apply_spi.h"
#include "spock_exception_handler.h"
#include "spock_common.h"
#include "spock_readonly.h"
#include "spock.h"
PGDLLEXPORT void spock_apply_main(Datum main_arg);
static bool in_remote_transaction = false;
static bool first_begin_at_startup = true;
static XLogRecPtr remote_origin_lsn = InvalidXLogRecPtr;
static RepOriginId remote_origin_id = InvalidRepOriginId;
static TimeOffset apply_delay = 0;
static Oid QueueRelid = InvalidOid;
static List *SyncingTables = NIL;
SpockApplyWorker *MyApplyWorker = NULL;
SpockSubscription *MySubscription = NULL;
int my_exception_log_index = -1;
static PGconn *applyconn = NULL;
typedef struct SpockApplyFunctions
{
spock_apply_begin_fn on_begin;
spock_apply_commit_fn on_commit;
spock_apply_insert_fn do_insert;
spock_apply_update_fn do_update;
spock_apply_delete_fn do_delete;
spock_apply_can_mi_fn can_multi_insert;
spock_apply_mi_add_tuple_fn multi_insert_add_tuple;
spock_apply_mi_finish_fn multi_insert_finish;
} SpockApplyFunctions;
static SpockApplyFunctions apply_api =
{
.on_begin = spock_apply_heap_begin,
.on_commit = spock_apply_heap_commit,
.do_insert = spock_apply_heap_insert,
.do_update = spock_apply_heap_update,
.do_delete = spock_apply_heap_delete,
.can_multi_insert = spock_apply_heap_can_mi,
.multi_insert_add_tuple = spock_apply_heap_mi_add_tuple,
.multi_insert_finish = spock_apply_heap_mi_finish
};
/* Number of tuples inserted after which we switch to multi-insert. */
#define MIN_MULTI_INSERT_TUPLES 5
static SpockRelation *last_insert_rel = NULL;
static int last_insert_rel_cnt = 0;
static bool use_multi_insert = false;
/*
* 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;
typedef struct SPKFlushPosition
{
dlist_node node;
XLogRecPtr local_end;
XLogRecPtr remote_end;
} SPKFlushPosition;
dlist_head lsn_mapping = DLIST_STATIC_INIT(lsn_mapping);
typedef struct ApplyExecState
{
EState *estate;
EPQState epqstate;
ResultRelInfo *resultRelInfo;
TupleTableSlot *slot;
} ApplyExecState;
struct ActionErrCallbackArg
{
const char *action_name;
SpockRelation *rel;
bool is_ddl_or_drop;
};
struct ActionErrCallbackArg errcallback_arg;
TransactionId remote_xid;
/*
* We enable skipping all data modification changes (INSERT, UPDATE, etc.) for
* the subscription if the remote transaction's finish LSN matches the sub_skip_lsn.
* Once we start skipping changes, we don't stop it until we skip all changes of
* the transaction even if spock.subscription is updated and MySubscription->skiplsn
* gets changed or reset during that. The sub_skip_lsn is cleared after successfully
* skipping the transaction or applying non-empty transaction. The latter prevents
* the mistakenly specified sub_skip_lsn from being left.
*/
static XLogRecPtr skip_xact_finish_lsn = InvalidXLogRecPtr;
#define is_skipping_changes() (unlikely(!XLogRecPtrIsInvalid(skip_xact_finish_lsn)))
/* Functions for skipping changes */
static void maybe_start_skipping_changes(XLogRecPtr finish_lsn);
static void stop_skipping_changes(void);
static void clear_subscription_skip_lsn(XLogRecPtr finish_lsn);
static void multi_insert_finish(void);
static void handle_queued_message(HeapTuple msgtup, bool tx_just_started);
static void handle_startup_param(const char *key, const char *value);
static bool parse_bool_param(const char *key, const char *value);
static void process_syncing_tables(XLogRecPtr end_lsn);
static void start_sync_worker(Name nspname, Name relname);
static bool should_log_exception(bool failed);
/*
* This function returns true when:
* - exception_logging is not equal to LOG_NONE, and
* - Subtransaction failed
* OR
* - Subtransaction succeeded, and
* - exception_behaviour is TRANSDISCARD or exception_logging is LOG_ALL
*/
static bool
should_log_exception(bool failed)
{
if (exception_logging != LOG_NONE)
{
if (failed)
return true;
else if (exception_logging == LOG_ALL ||
exception_behaviour == TRANSDISCARD)
return true;
}
return false;
}
/*
* Check if given relation is in process of being synchronized.
*
* TODO: performance
*/
static bool
should_apply_changes_for_rel(const char *nspname, const char *relname)
{
if (list_length(SyncingTables) > 0)
{
ListCell *lc;
foreach(lc, SyncingTables)
{
SpockSyncStatus *sync = (SpockSyncStatus *) lfirst(lc);
if (namestrcmp(&sync->nspname, nspname) == 0 &&
namestrcmp(&sync->relname, relname) == 0 &&
(sync->status != SYNC_STATUS_READY &&
!(sync->status == SYNC_STATUS_SYNCDONE &&
sync->statuslsn <= replorigin_session_origin_lsn)))
return false;
}
}
return true;
}
/*
* Prepare apply state details for errcontext or direct logging.
*
* This callback could be invoked at all sorts of weird times
* so it should assume as little as psosible about the invoking
* context.
*/
static void
format_action_description(
StringInfo si,
const char *action_name,
SpockRelation *rel,
bool is_ddl_or_drop)
{
appendStringInfoString(si, "apply ");
appendStringInfoString(si,
action_name == NULL ? "(unknown action)" : action_name);
if (rel != NULL &&
rel->nspname != NULL
&& rel->relname != NULL
&& !is_ddl_or_drop)
{
appendStringInfo(si, " from remote relation %s.%s",
rel->nspname, rel->relname);
}
appendStringInfo(si,
" in commit before %X/%X, xid %u committed at %s (action #%u)",
(uint32) (replorigin_session_origin_lsn >> 32),
(uint32) replorigin_session_origin_lsn,
remote_xid,
timestamptz_to_str(replorigin_session_origin_timestamp),
xact_action_counter);
if (replorigin_session_origin != InvalidRepOriginId)
{
appendStringInfo(si, " from node replorigin %u",
replorigin_session_origin);
}
if (remote_origin_id != InvalidRepOriginId)
{
appendStringInfo(si, " forwarded from commit %X/%X on node %u",
(uint32) (remote_origin_lsn >> 32),
(uint32) remote_origin_lsn,
remote_origin_id);
}
}
static void
action_error_callback(void *arg)
{
StringInfoData si;
initStringInfo(&si);
format_action_description(&si,
errcallback_arg.action_name,
errcallback_arg.rel,
errcallback_arg.is_ddl_or_drop);
errcontext("%s", si.data);
pfree(si.data);
}
/*
* Begin one step (one INSERT, UPDATE, etc) of a replication transaction.
*
* Start a transaction, if this is the first step (else we keep using the
* existing transaction).
* Also provide a global snapshot and ensure we run in ApplyMessageContext.
*/
static bool
begin_replication_step(void)
{
bool result = false;
/*
* spock doesn't have "statements" as such, so we'll report one statement
* per applied transaction. We must set the statement start time because
* StartTransaction() uses it to initialize the transaction cached
* timestamp used by current_timestamp. If we don't set it, every xact
* will get the same current_timestamp. See 2ndQuadrant/spock_internal#148
*/
SetCurrentStatementStartTimestamp();
if (!IsTransactionState())
{
StartTransactionCommand();
apply_api.on_begin();
result = true;
}
PushActiveSnapshot(GetTransactionSnapshot());
return result;
}
/*
* Finish up one step of a replication transaction.
* Callers of begin_replication_step() must also call this.
*
* We don't close out the transaction here, but we should increment
* the command counter to make the effects of this step visible.
*/
static void
end_replication_step(void)
{
PopActiveSnapshot();
CommandCounterIncrement();
MemoryContextSwitchTo(MessageContext);
}
static void
handle_begin(StringInfo s)
{
SpockExceptionLog *exception_log;
SpockExceptionLog *new_elog_entry;
XLogRecPtr commit_lsn;
TimestampTz commit_time;
bool slot_found = false;
int sub_name_len = strlen(MySubscription->name);
char *slot_name;
/*
* To get here we must have connected successfully and the
* replication stream is delivering the first transaction.
* At this point we switch to restart_delay_on_exception
* assuming that we are just replicating a transaction without
* exception handling.
*/
MySpockWorker->restart_delay = restart_delay_on_exception;
xact_action_counter = 1;
errcallback_arg.action_name = "BEGIN";
spock_read_begin(s, &commit_lsn, &commit_time, &remote_xid);
maybe_start_skipping_changes(commit_lsn);
replorigin_session_origin_timestamp = commit_time;
replorigin_session_origin_lsn = commit_lsn;
remote_origin_id = InvalidRepOriginId;
/*
* We either create a new shared memory struct in the error log for
* ourselves if it doesn't exist, or check the commit lsn of the existing
* entry. There are four cases here:
*
* 1. The error log is empty and we need to create a new slot anyway.
*
* 2. The error log is not empty, but we didn't find ourselves in any of
* the entries. We need to create a slot here as well.
*
* 3. The error log is not empty and we found our entry, but the commit
* lsn does not match. We simply update the commit lsn and move on. This
* case happens when we have not errored out previously.
*
* 4. The error log is not empty, we found our entry and the commit lsn.
* This would mean that we previously errored and restarted. We set the
* MyApplyWorker->use_try_block = true.
*/
if (first_begin_at_startup)
{
first_begin_at_startup = false;
for (int i = 0; i <= SpockCtx->total_workers; i++)
{
exception_log = &exception_log_ptr[i];
slot_name = NameStr(exception_log->slot_name);
if (strncmp(slot_name, MySubscription->name, sub_name_len) == 0)
{
/* We found our slot in shared memory. */
slot_found = true;
my_exception_log_index = i;
/*
* Break out out of the loop whether we've found the commit
* LSN or not since we have already found our slot
*/
break;
}
}
if (!slot_found)
{
int free_slot_index = -1;
/*
* If we don't find ourselves in shared memory, then we get the
* pointer to the first free slot we remembered earlier, and fill
* in our slot name, commit_lsn and set local_tuple = NULL
*/
MyApplyWorker->use_try_block = false;
/*
* Let's acquire an exclusive lock to ensure no changes are made
* by another process while we attempt to check again subscription
* name exists, if so, we'll take that. Otherwise, remember the
* first free slot index.
*/
LWLockAcquire(SpockCtx->lock, LW_EXCLUSIVE);
for (int i = 0; i <= SpockCtx->total_workers; i++)
{
exception_log = &exception_log_ptr[i];
slot_name = NameStr(exception_log->slot_name);
if (strncmp(slot_name, MySubscription->name, sub_name_len) == 0)
{
/* We found our slot in shared memory. */
slot_found = true;
my_exception_log_index = i;
/*
* Break out out of the loop whether we've found the commit
* LSN or not since we have already found our slot
*/
break;
}
if (free_slot_index < 0 && strlen(slot_name) == 0)
{
free_slot_index = i;
}
}
/* TODO: What to do if we can't find a free slot? */
if (free_slot_index == -1)
{
/* no free entries found. */
elog(ERROR, "SPOCK %s: unable to find an empty exception log slot.",
MySubscription->name);
}
/* We didn't find a slot, but we have a valid index. */
if (!slot_found)
{
/* TODO: What happens if a subscription is dropped? Memory leak */
new_elog_entry = &exception_log_ptr[free_slot_index];
namestrcpy(&new_elog_entry->slot_name, MySubscription->name);
/*
* Redundant, since it's happening below. But we'll have it for
* now
*/
new_elog_entry->commit_lsn = commit_lsn;
new_elog_entry->local_tuple = NULL;
my_exception_log_index = free_slot_index;
}
/* We've occupied the free slot. Let's release the lock now. */
LWLockRelease(SpockCtx->lock);
}
}
if (slot_found)
{
/*
* If we find our slot in shared memory, check for commit LSN
*/
if (exception_log->commit_lsn == commit_lsn)
{
MyApplyWorker->use_try_block = true;
/*
* If we unexpectedly terminate again with error during
* exception handling, don't go into a fast error loop.
*/
MySpockWorker->restart_delay = restart_delay_default;
}
}
/*
* Yes, it is because all of this information should have been
* part of the SpockApplyWorker struct instead its own shared
* memory array. The overall process structure of the supervisor,
* the db-level manager and the apply-worker is taking care of
* this shared memory already.
*/
exception_log = &exception_log_ptr[my_exception_log_index];
exception_log->commit_lsn = commit_lsn;
VALGRIND_PRINTF("SPOCK_APPLY: begin %u\n", remote_xid);
/* don't want the overhead otherwise */
if (apply_delay > 0)
{
TimestampTz current;
current = GetCurrentIntegerTimestamp();
/* ensure no weirdness due to clock drift */
if (current > replorigin_session_origin_timestamp)
{
long sec;
int usec;
current = TimestampTzPlusMilliseconds(current,
-apply_delay);
TimestampDifference(current, replorigin_session_origin_timestamp,
&sec, &usec);
/* FIXME: deal with overflow? */
pg_usleep(usec + (sec * USECS_PER_SEC));
}
}
in_remote_transaction = true;
pgstat_report_activity(STATE_RUNNING, NULL);
}
/*
* Handle COMMIT message.
*/
static void
handle_commit(StringInfo s)
{
XLogRecPtr commit_lsn;
XLogRecPtr end_lsn;
TimestampTz commit_time;
errcallback_arg.action_name = "COMMIT";
xact_action_counter++;
spock_read_commit(s, &commit_lsn, &end_lsn, &commit_time);
Assert(commit_time == replorigin_session_origin_timestamp);
if (is_skipping_changes())
{
stop_skipping_changes();
/*
* Start a new transaction to clear the subskiplsn, if not started
* yet.
*/
if (!IsTransactionState())
StartTransactionCommand();
}
if (IsTransactionState())
{
SPKFlushPosition *flushpos;
/*
* The transaction is either non-empty or skipped, so we clear the
* subskiplsn.
*/
clear_subscription_skip_lsn(end_lsn);
multi_insert_finish();
apply_api.on_commit();
/* We need to write end_lsn to the commit record. */
replorigin_session_origin_lsn = end_lsn;
/* Have the commit code adjust our logical clock if needed */
remoteTransactionStopTimestamp = commit_time;
CommitTransactionCommand();
remoteTransactionStopTimestamp = 0;
MemoryContextSwitchTo(TopMemoryContext);
/* Track commit lsn */
flushpos = (SPKFlushPosition *) palloc(sizeof(SPKFlushPosition));
flushpos->local_end = XactLastCommitEnd;
flushpos->remote_end = end_lsn;
dlist_push_tail(&lsn_mapping, &flushpos->node);
MemoryContextSwitchTo(MessageContext);
}
/*
* If the xact 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.
*
* This is only necessary when we're streaming data from one peer (A) that
* in turn receives from other peers (B, C), and we plan to later switch
* to replaying directly from B and/or C, no longer receiving forwarded
* xacts from A. When we do the switchover we need to know the right place
* at which to start replay from B and C. We don't actually do that yet,
* but we'll want to be able to do cascaded initialisation in future, so
* it's worth keeping track.
*
* A failure can occur here (see #79) if there's a cascading replication
* configuration like:
*
* X--> Y -> Z | ^ | | \---------/
*
* where the direct and indirect connections from X to Z use different
* replication sets so as not to conflict, and where Y and Z are on the
* same PostgreSQL instance. In this case our attempt to advance the
* replication identifier here will ERROR because it's already in use for
* the direct connection from X to Z. So don't do that.
*/
#if 0
/*
* XXX: This needs to be redone with Spock style forwarding in mind.
*/
if (remote_origin_id != InvalidRepOriginId &&
remote_origin_id != replorigin_session_origin)
{
Relation replorigin_rel;
elog(DEBUG3, "SPOCK %s: advancing origin oid %u for forwarded "
"row to %X/%X",
MySubscription->name,
remote_origin_id,
(uint32) (XactLastCommitEnd >> 32), (uint32) XactLastCommitEnd);
replorigin_rel = table_open(ReplicationOriginRelationId, RowExclusiveLock);
replorigin_advance(remote_origin_id, remote_origin_lsn,
XactLastCommitEnd, false, false /* XXX ? */ );
table_close(replorigin_rel, RowExclusiveLock);
}
#endif
in_remote_transaction = false;
/*
* Stop replay if we're doing limited replay and we've replayed up to the
* last record we're supposed to process.
*/
if (MyApplyWorker->replay_stop_lsn != InvalidXLogRecPtr
&& MyApplyWorker->replay_stop_lsn <= end_lsn)
{
ereport(LOG,
(errmsg("SPOCK %s: %s finished processing; replayed "
"to %X/%X of required %X/%X",
MySubscription->name,
MySpockWorker->worker_type == SPOCK_WORKER_SYNC ? "sync" : "apply",
(uint32) (end_lsn >> 32), (uint32) end_lsn,
(uint32) (MyApplyWorker->replay_stop_lsn >> 32),
(uint32) MyApplyWorker->replay_stop_lsn)));
/*
* If this is sync worker, update syncing table state to done.
*/
if (MySpockWorker->worker_type == SPOCK_WORKER_SYNC)
{
StartTransactionCommand();
set_table_sync_status(MyApplyWorker->subid,
NameStr(MySpockWorker->worker.sync.nspname),
NameStr(MySpockWorker->worker.sync.relname),
SYNC_STATUS_SYNCDONE, end_lsn);
CommitTransactionCommand();
}
/*
* Flush all writes so the latest position can be reported back to the
* sender.
*/
XLogFlush(GetXLogWriteRecPtr());
/*
* Disconnect.
*
* This needs to happen before the spock_sync_worker_finish() call
* otherwise slot drop will fail.
*/
PQfinish(applyconn);
/*
* If this is sync worker, finish it.
*/
if (MySpockWorker->worker_type == SPOCK_WORKER_SYNC)
spock_sync_worker_finish();
/* Stop gracefully */
proc_exit(0);
}
VALGRIND_PRINTF("SPOCK_APPLY: commit %u\n", remote_xid);
xact_action_counter = 0;
remote_xid = InvalidTransactionId;
/*
* This is the only place we can reset the use_try_block = false without
* any risk of going into the error deathloop
*/
MyApplyWorker->use_try_block = false;
process_syncing_tables(end_lsn);
/*
* Ensure any pending signals/self-notifies are sent out.
*
* Note that there is a possibility that this will result in an ERROR,
* which will result in the apply worker being killed and restarted. As
* the notification queues have already been flushed, the same error won't
* occur again, however if errors continue, they will dramatically slow
* down - but not stop - replication.
*
* For PG15 and above, such notifications are sent at transaction commit.
* (This is also true of previous version branches that received a fix[1]
* but where ProcessCompletedNotifies() was converted to a no-op routine
* to avoid breaking ABI.)
*
* [1] -- Discussion:
* https://www.postgresql.org/message-id/flat/[email protected]
*/
#if PG_VERSION_NUM < 150000
ProcessCompletedNotifies();
#endif
pgstat_report_activity(STATE_IDLE, NULL);
}
/*
* Handle ORIGIN message.
*/
static void
handle_origin(StringInfo s)
{
/*
* ORIGIN message can only come inside remote transaction and before any
* actual writes.
*/
if (!in_remote_transaction || IsTransactionState())
elog(ERROR, "SPOCK %s: ORIGIN message sent out of order",
MySubscription->name);
/*
* Read the message and adjust the replorigin_session_origin to the real
* origin_id. PostgreSQL builtin logical replication uses the non-sensical
* roident, which is linked to the slot of the provider and has nothing to
* do with the actual origin of the original transaction.
*/
remote_origin_id = spock_read_origin(s, &remote_origin_lsn);
replorigin_session_origin = remote_origin_id;
}
/*
* Handle RELATION message.
*
* Note we don't do validation against local schema here. The validation is
* posponed until first change for given relation comes.
*/
static void
handle_relation(StringInfo s)
{
multi_insert_finish();
(void) spock_read_rel(s);
}
static void
handle_insert(StringInfo s)
{
SpockTupleData newtup;
SpockTupleData *oldtup = NULL;
HeapTuple localtup = NULL;
SpockRelation *rel;
ErrorData *edata;
bool started_tx;
bool failed = false;
char *action_name = "INSERT";
/*
* Quick return if we are skipping data modification changes.
*/
if (is_skipping_changes())
return;
started_tx = begin_replication_step();
errcallback_arg.action_name = "INSERT";
xact_action_counter++;
rel = spock_read_insert(s, RowExclusiveLock, &newtup);
errcallback_arg.rel = rel;
/* If in list of relations which are being synchronized, skip. */
if (!should_apply_changes_for_rel(rel->nspname, rel->relname))
{
spock_relation_close(rel, NoLock);
end_replication_step();
return;
}
/*
* Handle multi_insert capabilities. TODO: Don't do multi- or
* batch-inserts when in use_try_block mode
*/
if (use_multi_insert && MyApplyWorker->use_try_block == false)
{
if (rel != last_insert_rel)
{
multi_insert_finish();
/* Fall through to normal insert. */
}
else
{
apply_api.multi_insert_add_tuple(rel, &newtup);
last_insert_rel_cnt++;
return;
}
}
else if (spock_batch_inserts &&
RelationGetRelid(rel->rel) != QueueRelid &&
apply_api.can_multi_insert &&
apply_api.can_multi_insert(rel) &&
MyApplyWorker->use_try_block == false)
{
if (rel != last_insert_rel)
{
last_insert_rel = rel;
last_insert_rel_cnt = 0;
}
else if (last_insert_rel_cnt++ >= MIN_MULTI_INSERT_TUPLES)
{
use_multi_insert = true;
last_insert_rel_cnt = 0;
}
}
/* Normal insert. */
/* TODO: Handle multiple inserts */
if (MyApplyWorker->use_try_block)
{
PG_TRY();
{
exception_command_counter++;
BeginInternalSubTransaction(NULL);
apply_api.do_insert(rel, &newtup);
}
PG_CATCH();
{
failed = true;
RollbackAndReleaseCurrentSubTransaction();
edata = CopyErrorData();
}
PG_END_TRY();
if (!failed)
{
if (exception_behaviour == TRANSDISCARD)
RollbackAndReleaseCurrentSubTransaction();
else
ReleaseCurrentSubTransaction();
}
/* Let's create an exception log entry if true. */
if (should_log_exception(failed))
add_entry_to_exception_log(remote_origin_id,
replorigin_session_origin_timestamp,
remote_xid,
0, 0,
rel, localtup, oldtup, &newtup,
NULL, NULL,
action_name,
(failed) ? edata->message : NULL);
}
else
{
apply_api.do_insert(rel, &newtup);
}
/* if INSERT was into our queue, process the message. */
if (RelationGetRelid(rel->rel) == QueueRelid)
{
HeapTuple ht;
LockRelId lockid = rel->rel->rd_lockInfo.lockRelId;
Relation qrel;
multi_insert_finish();
MemoryContextSwitchTo(MessageContext);
ht = heap_form_tuple(RelationGetDescr(rel->rel),
newtup.values, newtup.nulls);
LockRelationIdForSession(&lockid, RowExclusiveLock);
spock_relation_close(rel, NoLock);
end_replication_step();
apply_api.on_commit();
handle_queued_message(ht, started_tx);
heap_freetuple(ht);
qrel = table_open(QueueRelid, RowExclusiveLock);
UnlockRelationIdForSession(&lockid, RowExclusiveLock);
table_close(qrel, NoLock);
apply_api.on_begin();
MemoryContextSwitchTo(MessageContext);
}
else
{
spock_relation_close(rel, NoLock);
end_replication_step();
}
}
static void
multi_insert_finish(void)
{
if (use_multi_insert && last_insert_rel_cnt)
{
const char *old_action = errcallback_arg.action_name;
SpockRelation *old_rel = errcallback_arg.rel;
errcallback_arg.action_name = "multi INSERT";
errcallback_arg.rel = last_insert_rel;
apply_api.multi_insert_finish(last_insert_rel);
spock_relation_close(last_insert_rel, NoLock);
use_multi_insert = false;
last_insert_rel = NULL;
last_insert_rel_cnt = 0;
errcallback_arg.rel = old_rel;
errcallback_arg.action_name = old_action;
}
}
static void
handle_update(StringInfo s)
{
SpockTupleData oldtup;
SpockTupleData newtup;
SpockRelation *rel;
ErrorData *edata = NULL;
HeapTuple localtup;
bool hasoldtup;
bool failed = false;
/*
* Quick return if we are skipping data modification changes.