forked from pgEdge/spock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spock_apply.c
2162 lines (1803 loc) · 55.2 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-2023, 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 "commands/async.h"
#include "commands/dbcommands.h"
#include "commands/sequence.h"
#include "commands/tablecmds.h"
#include "commands/trigger.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/jsonb.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/snapmgr.h"
#if PG_VERSION_NUM >= 160000
#include "utils/usercontext.h"
#endif
#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.h"
PGDLLEXPORT void spock_apply_main(Datum main_arg);
static bool in_remote_transaction = false;
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;
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;
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);
/*
* 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);
}
static bool
ensure_transaction(void)
{
if (IsTransactionState())
{
if (CurrentMemoryContext != MessageContext)
MemoryContextSwitchTo(MessageContext);
return 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();
StartTransactionCommand();
apply_api.on_begin();
MemoryContextSwitchTo(MessageContext);
return true;
}
static void
handle_begin(StringInfo s)
{
XLogRecPtr commit_lsn;
TimestampTz commit_time;
xact_action_counter = 1;
errcallback_arg.action_name = "BEGIN";
spock_read_begin(s, &commit_lsn, &commit_time, &remote_xid);
replorigin_session_origin_timestamp = commit_time;
replorigin_session_origin_lsn = commit_lsn;
remote_origin_id = InvalidRepOriginId;
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 (IsTransactionState())
{
SPKFlushPosition *flushpos;
multi_insert_finish();
apply_api.on_commit();
/* We need to write end_lsn to the commit record. */
replorigin_session_origin_lsn = end_lsn;
CommitTransactionCommand();
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 (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);
}
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;
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)
{
char *origin;
/*
* 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);
/* We have to start transaction here so that we can work with origins. */
ensure_transaction();
origin = spock_read_origin(s, &remote_origin_lsn);
remote_origin_id = replorigin_by_name(origin, true);
}
/*
* 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;
SpockRelation *rel;
#if PG_VERSION_NUM >= 160000
UserContext ucxt;
#endif
bool started_tx = ensure_transaction();
PushActiveSnapshot(GetTransactionSnapshot());
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);
PopActiveSnapshot();
CommandCounterIncrement();
return;
}
/* Make sure that any user-supplied code runs as the table owner. */
SwitchToUntrustedUser(rel->rel->rd_rel->relowner, &ucxt);
/* Handle multi_insert capabilities. */
if (use_multi_insert)
{
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))
{
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. */
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);
RestoreUserContext(&ucxt);
spock_relation_close(rel, NoLock);
PopActiveSnapshot();
CommandCounterIncrement();
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);
// if (oldxid != GetTopTransactionId())
// CommitTransactionCommand();
}
else
{
RestoreUserContext(&ucxt);
spock_relation_close(rel, NoLock);
PopActiveSnapshot();
CommandCounterIncrement();
}
}
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;
#if PG_VERSION_NUM >= 160000
UserContext ucxt;
#endif
bool hasoldtup;
errcallback_arg.action_name = "UPDATE";
xact_action_counter++;
ensure_transaction();
multi_insert_finish();
PushActiveSnapshot(GetTransactionSnapshot());
rel = spock_read_update(s, RowExclusiveLock, &hasoldtup, &oldtup,
&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);
PopActiveSnapshot();
CommandCounterIncrement();
return;
}
/* Make sure that any user-supplied code runs as the table owner. */
SwitchToUntrustedUser(rel->rel->rd_rel->relowner, &ucxt);
apply_api.do_update(rel, hasoldtup ? &oldtup : &newtup, &newtup);
RestoreUserContext(&ucxt);
spock_relation_close(rel, NoLock);
PopActiveSnapshot();
CommandCounterIncrement();
}
static void
handle_delete(StringInfo s)
{
SpockTupleData oldtup;
SpockRelation *rel;
#if PG_VERSION_NUM >= 160000
UserContext ucxt;
#endif
memset(&errcallback_arg, 0, sizeof(struct ActionErrCallbackArg));
xact_action_counter++;
ensure_transaction();
multi_insert_finish();
PushActiveSnapshot(GetTransactionSnapshot());
rel = spock_read_delete(s, RowExclusiveLock, &oldtup);
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);
PopActiveSnapshot();
CommandCounterIncrement();
return;
}
/* Make sure that any user-supplied code runs as the table owner. */
SwitchToUntrustedUser(rel->rel->rd_rel->relowner, &ucxt);
apply_api.do_delete(rel, &oldtup);
RestoreUserContext(&ucxt);
spock_relation_close(rel, NoLock);
PopActiveSnapshot();
CommandCounterIncrement();
}
inline static bool
getmsgisend(StringInfo msg)
{
return msg->cursor == msg->len;
}
static void
handle_startup(StringInfo s)
{
uint8 msgver = pq_getmsgbyte(s);
if (msgver != 1)
elog(ERROR, "SPOCK %s: Expected startup message version 1, but got %u",
MySubscription->name, msgver);
/*
* The startup message consists of null-terminated strings as key/value
* pairs. The first entry is always the format identifier.
*/
do {
const char *k, *v;
k = pq_getmsgstring(s);
if (strlen(k) == 0)
ereport(ERROR,
(errcode(ERRCODE_PROTOCOL_VIOLATION),
errmsg("SPOCK %s: invalid startup message: key has "
"zero length",
MySubscription->name)));
if (getmsgisend(s))
ereport(ERROR,
(errcode(ERRCODE_PROTOCOL_VIOLATION),
errmsg("SPOCK %s: invalid startup message: key '%s' "
"has no following value",
MySubscription->name, k)));
/* It's OK to have a zero length value */
v = pq_getmsgstring(s);
handle_startup_param(k, v);
} while (!getmsgisend(s));
}
static bool
parse_bool_param(const char *key, const char *value)
{
bool result;
if (!parse_bool(value, &result))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("SPOCK %s: couldn't parse value '%s' for key '%s' "
"as boolean",
MySubscription->name, value, key)));
return result;
}
static void
handle_startup_param(const char *key, const char *value)
{
elog(DEBUG2, "SPOCK %s: apply got spock startup msg param %s=%s",
MySubscription->name, key, value);
if (strcmp(key, "pg_version") == 0)
elog(DEBUG1, "SPOCK %s: upstream Pg version is %s",
MySubscription->name, value);
if (strcmp(key, "encoding") == 0)
{
int encoding = pg_char_to_encoding(value);
if (encoding != GetDatabaseEncoding())
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("SPOCK %s: expected encoding=%s from upstream "
"but got %s",
MySubscription->name,
GetDatabaseEncodingName(), value)));
}
if (strcmp(key, "forward_changeset_origins") == 0)
{
bool fwd = parse_bool_param(key, value);
/* FIXME: Store this somewhere */
elog(DEBUG1, "SPOCK %s: changeset origin forwarding enabled: %s",
MySubscription->name, fwd ? "t" : "f");
}
/*
* We just ignore a bunch of parameters here because we specify what we
* require when we send our params to the upstream. It's required to ERROR
* if it can't match what we asked for. It may send the startup message
* first, but it'll be followed by an ERROR if it does. There's no need
* to check params we can't do anything about mismatches of, like protocol
* versions and type sizes.
*/
}
static RangeVar *
parse_relation_message(Jsonb *message)
{
JsonbIterator *it;
JsonbValue v;
int r;
int level = 0;
char *key = NULL;
char **parse_res = NULL;
char *nspname = NULL;
char *relname = NULL;
/* Parse and validate the json message. */
if (!JB_ROOT_IS_OBJECT(message))
elog(ERROR, "SPOCK %s: malformed message in queued message tuple: "
"root is not object",
MySubscription->name);
it = JsonbIteratorInit(&message->root);
while ((r = JsonbIteratorNext(&it, &v, false)) != WJB_DONE)
{
if (level == 0 && r != WJB_BEGIN_OBJECT)
elog(ERROR, "SPOCK %s: root element needs to be an object",
MySubscription->name);
else if (level == 0 && r == WJB_BEGIN_OBJECT)
{
level++;
}
else if (level == 1 && r == WJB_KEY)
{
if (strncmp(v.val.string.val, "schema_name", v.val.string.len) == 0)
parse_res = &nspname;
else if (strncmp(v.val.string.val, "table_name", v.val.string.len) == 0)
parse_res = &relname;
else
elog(ERROR, "SPOCK %s: unexpected key: %s",
MySubscription->name,
pnstrdup(v.val.string.val, v.val.string.len));
key = v.val.string.val;
}
else if (level == 1 && r == WJB_VALUE)
{
if (!key)
elog(ERROR, "SPOCK %s: in wrong state when parsing key",
MySubscription->name);
if (v.type != jbvString)
elog(ERROR, "SPOCK %s: unexpected type for key '%s': %u",
MySubscription->name, key, v.type);
*parse_res = pnstrdup(v.val.string.val, v.val.string.len);
}
else if (level == 1 && r != WJB_END_OBJECT)
{
elog(ERROR, "SPOCK %s: unexpected content: %u at level %d",
MySubscription->name, r, level);
}
else if (r == WJB_END_OBJECT)
{
level--;
parse_res = NULL;
key = NULL;
}
else
elog(ERROR, "SPOCK %s: unexpected content: %u at level %d",
MySubscription->name, r, level);
}
/* Check if we got both schema and table names. */
if (!nspname)
elog(ERROR, "SPOCK %s: missing schema_name in relation message",
MySubscription->name);
if (!relname)
elog(ERROR, "SPOCK %s: missing table_name in relation message",
MySubscription->name);
return makeRangeVar(nspname, relname, -1);
}
/*
* Handle TRUNCATE message comming via queue table.
*/
static void
handle_truncate(QueuedMessage *queued_message)
{
RangeVar *rv;
/*
* If table doesn't exist locally, it can't be subscribed.
*
* TODO: should we error here?
*/
rv = parse_relation_message(queued_message->message);
/* If in list of relations which are being synchronized, skip. */
if (!should_apply_changes_for_rel(rv->schemaname, rv->relname))
return;
truncate_table(rv->schemaname, rv->relname);
}
/*
* Handle TABLESYNC message comming via queue table.
*/
static void
handle_table_sync(QueuedMessage *queued_message)
{
RangeVar *rv;
MemoryContext oldcontext;
SpockSyncStatus *oldsync;
SpockSyncStatus *newsync;
rv = parse_relation_message(queued_message->message);
oldsync = get_table_sync_status(MyApplyWorker->subid, rv->schemaname,
rv->relname, true);
if (oldsync)
{
elog(INFO, "SPOCK %s: table sync came from queue for table %s.%s "
"which already being synchronized, skipping",
MySubscription->name,
rv->schemaname, rv->relname);
return;
}
/* Keep the lists persistent. */
oldcontext = MemoryContextSwitchTo(TopMemoryContext);
newsync = palloc0(sizeof(SpockSyncStatus));
MemoryContextSwitchTo(oldcontext);