-
Notifications
You must be signed in to change notification settings - Fork 9
/
bdr_seq.c
1565 lines (1299 loc) · 38.9 KB
/
bdr_seq.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_seq.c
* A distributed sequence implementation.
*
* Replication???
*
* Copyright (C) 2012-2015, PostgreSQL Global Development Group
*
* IDENTIFICATION
* bdr_seq.c
*
* -------------------------------------------------------------------------
*/
#include "postgres.h"
#include "bdr_config.h"
#ifndef HAVE_SEQAM
#error bdr_seq.h only compiles when sequence access methods are available in Pg
#endif
#include "bdr.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "access/reloptions.h"
#include "access/seqam.h"
#include "access/transam.h"
#include "access/xact.h"
#include "catalog/namespace.h"
#include "catalog/pg_type.h"
#include "commands/sequence.h"
#include "executor/spi.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "storage/bufmgr.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "storage/lmgr.h"
#include "storage/proc.h"
#include "storage/sinvaladt.h"
typedef struct BdrSequencerSlot
{
Oid database_oid;
int nnodes;
Latch *proclatch;
} BdrSequencerSlot;
typedef struct BdrSequencerControl
{
int next_slot;
BdrSequencerSlot slots[FLEXIBLE_ARRAY_MEMBER];
} BdrSequencerControl;
typedef struct BdrSequenceValues {
int64 start_value;
int64 next_value;
int64 end_value;
} BdrSequenceValues;
/* global sequence relids */
Oid BdrSeqamOid = InvalidOid;
Oid BdrSequenceValuesRelid; /* bdr_sequence_values */
Oid BdrSequenceElectionsRelid; /* bdr_sequence_elections */
Oid BdrVotesRelid; /* bdr_votes */
/* Our offset within the shared memory array of registered sequence managers */
static int seq_slot = -1;
static BdrSequencerControl *BdrSequencerCtl = NULL;
/* how many nodes have we built shmem for */
static size_t bdr_seq_nsequencers = 0;
static shmem_startup_hook_type prev_shmem_startup_hook = NULL;
static bool bdr_seq_pending_wakeup = false;
static relopt_kind bdr_seq_relopt_kind = RELOPT_KIND_SEQUENCE;
/* vote, the logic is in a function */
const char* vote_sql = ""
"SELECT bdr.bdr_sequencer_vote($1, $2, $3, $4);\n";
const char *start_elections_sql =
"WITH to_be_updated_sequences AS (\n"
" SELECT\n"
" pg_namespace.nspname AS seqschema,\n"
" seq.relname AS seqname,\n"
" COUNT(bdr_sequence_values) AS open_seq_chunks,\n"
" GREATEST(COALESCE((\n"
" SELECT max(upper(seqrange))\n"
" FROM bdr_sequence_values max_val\n"
" WHERE\n"
" max_val.seqschema = pg_namespace.nspname\n"
" AND max_val.seqname = seq.relname\n"
" ), 0), (SELECT start_value FROM pg_sequence_parameters(seq.oid)))\n"
" AS current_max,\n"
" seq.cache_chunks\n"
" FROM\n"
" (SELECT\n"
" pg_class.oid,\n"
" pg_class.relnamespace,\n"
" pg_class.relname,\n"
" COALESCE((SELECT split_part(o, '=', 2)::int\n"
" FROM unnest(pg_class.reloptions) o\n"
" WHERE split_part(o, '=', 1) = 'cache_chunks'), 5)\n"
" AS cache_chunks\n"
" FROM\n"
" pg_class\n"
" WHERE\n"
" pg_class.relkind = 'S' AND\n"
" pg_class.relam = (SELECT oid FROM pg_seqam WHERE seqamname = 'bdr')\n"
" ) seq\n"
" JOIN pg_namespace ON (seq.relnamespace = pg_namespace.oid)\n"
" LEFT JOIN bdr_sequence_values ON (\n"
" bdr_sequence_values.seqschema = pg_namespace.nspname\n"
" AND bdr_sequence_values.seqname = seq.relname\n"
" AND bdr_sequence_values.emptied = false\n"
" AND bdr_sequence_values.in_use = false\n"
" AND bdr_sequence_values.failed = false\n"
" AND bdr_sequence_values.owning_sysid = $1\n"
" AND bdr_sequence_values.owning_tlid = $2\n"
" AND bdr_sequence_values.owning_dboid = $3\n"
" AND bdr_sequence_values.owning_riname = $4\n"
" )\n"
" GROUP BY\n"
" seq.relname,\n"
" pg_namespace.nspname,\n"
" seq.oid,\n"
" seq.cache_chunks\n"
" HAVING\n"
" count(bdr_sequence_values) <= cache_chunks\n"
"),\n"
"to_be_inserted_chunks AS (\n"
" SELECT\n"
" seqschema,\n"
" seqname,\n"
" current_max,\n"
" generate_series(\n"
" current_max,\n"
" -- 10000 is the chunk size, -1 is to get < instead <= out of generate_series\n"
" current_max + 10000 * (cache_chunks - open_seq_chunks) - 1,\n"
" 10000) chunk_start\n"
" FROM to_be_updated_sequences\n"
" LIMIT 500\n"
"),\n"
"inserted_chunks AS (\n"
" INSERT INTO bdr_sequence_elections(\n"
" owning_sysid,\n"
" owning_tlid,\n"
" owning_dboid,\n"
" owning_riname,\n"
" owning_election_id,\n"
" vote_type,\n"
" open,\n"
" seqschema,\n"
" seqname,\n"
" seqrange\n"
" )\n"
" SELECT\n"
" $1,\n"
" $2,\n"
" $3,\n"
" $4,\n"
" (\n"
" SELECT COALESCE(max(owning_election_id), 0)\n"
" FROM bdr_sequence_elections biggest\n"
" WHERE\n"
" biggest.owning_sysid = $1\n"
" AND biggest.owning_tlid = $2\n"
" AND biggest.owning_dboid = $3\n"
" AND biggest.owning_riname = $4\n"
" ) + row_number() OVER (),\n"
" 'sequence',\n"
" true AS open,\n"
" seqschema,\n"
" seqname,\n"
" int8range(chunk_start, chunk_start + 10000) AS seqrange\n"
" FROM to_be_inserted_chunks\n"
" RETURNING\n"
" seqschema,\n"
" seqname,\n"
" seqrange\n"
")\n"
"\n"
"INSERT INTO bdr_sequence_values(\n"
" owning_sysid,\n"
" owning_tlid,\n"
" owning_dboid,\n"
" owning_riname,\n"
" seqschema,\n"
" seqname,\n"
" confirmed,\n"
" in_use,\n"
" emptied,\n"
" seqrange\n"
")\n"
"SELECT\n"
" $1,\n"
" $2,\n"
" $3,\n"
" $4,\n"
" seqschema,\n"
" seqname,\n"
" false AS confirmed,\n"
" false AS in_use,\n"
" false AS emptied,\n"
" int8range(chunk_start, chunk_start + 10000)\n"
"FROM to_be_inserted_chunks\n"
"-- force evaluation \n"
"WHERE (SELECT count(*) FROM inserted_chunks) >= 0\n"
"RETURNING\n"
" owning_sysid,\n"
" owning_tlid,\n"
" owning_dboid,\n"
" owning_riname,\n"
" seqschema,\n"
" seqname,\n"
" confirmed,\n"
" emptied,\n"
" seqrange\n"
;
const char *tally_elections_sql =
"WITH tallied_votes AS (\n"
"SELECT\n"
" election.owning_sysid,\n"
" election.owning_tlid,\n"
" election.owning_dboid,\n"
" election.owning_riname,\n"
" election.owning_election_id,\n"
" election.seqschema,\n"
" election.seqname,\n"
" election.seqrange,\n"
" SUM(COALESCE((vote.vote = true)::int, 0)) AS yays,\n"
" SUM(COALESCE((vote.vote = false)::int, 0)) AS nays,\n"
" COUNT(vote.vote) AS nr_votes,\n"
" /* majority of others */\n"
" COUNT(vote.vote) >= ceil($5/ 2.0) AS sufficient\n"
"FROM\n"
" bdr_sequence_elections election\n"
" LEFT JOIN bdr_votes vote ON (\n"
" election.owning_sysid = vote.vote_sysid\n"
" AND election.owning_tlid = vote.vote_tlid\n"
" AND election.owning_dboid = vote.vote_dboid\n"
" AND election.owning_riname = vote.vote_riname\n"
" AND election.owning_election_id = vote.vote_election_id\n"
" )\n"
"WHERE\n"
" election.open\n"
" AND election.owning_sysid = $1\n"
" AND election.owning_tlid = $2\n"
" AND election.owning_dboid = $3\n"
" AND election.owning_riname = $4\n"
"GROUP BY\n"
" election.owning_sysid,\n"
" election.owning_tlid,\n"
" election.owning_dboid,\n"
" election.owning_riname,\n"
" election.owning_election_id,\n"
" election.seqschema,\n"
" election.seqname,\n"
" election.seqrange\n"
"),\n"
"cast_votes AS (\n"
" UPDATE bdr_sequence_elections\n"
" SET\n"
" open = false,\n"
" success = (nays = 0 OR yays >= ceil($5/ 2.0))\n"
" FROM tallied_votes\n"
" WHERE\n"
" bdr_sequence_elections.owning_sysid = tallied_votes.owning_sysid\n"
" AND bdr_sequence_elections.owning_tlid = tallied_votes.owning_tlid\n"
" AND bdr_sequence_elections.owning_dboid = tallied_votes.owning_dboid\n"
" AND bdr_sequence_elections.owning_riname = tallied_votes.owning_riname\n"
" AND bdr_sequence_elections.owning_election_id = tallied_votes.owning_election_id\n"
" AND tallied_votes.sufficient\n"
" RETURNING bdr_sequence_elections.*\n"
"),\n"
"successfull_sequence_values AS (\n"
" UPDATE bdr_sequence_values\n"
" SET\n"
" confirmed = true\n"
" FROM cast_votes\n"
" WHERE\n"
" cast_votes.success = true\n"
" AND bdr_sequence_values.seqschema = cast_votes.seqschema\n"
" AND bdr_sequence_values.seqname = cast_votes.seqname\n"
" AND bdr_sequence_values.seqrange = cast_votes.seqrange\n"
" AND bdr_sequence_values.owning_sysid = $1\n"
" AND bdr_sequence_values.owning_tlid = $2\n"
" AND bdr_sequence_values.owning_dboid = $3\n"
" AND bdr_sequence_values.owning_riname = $4\n"
" RETURNING bdr_sequence_values.*\n"
"),\n"
"failed_sequence_values AS (\n"
" UPDATE bdr_sequence_values\n"
" SET\n"
" failed = true\n"
" FROM cast_votes\n"
" WHERE\n"
" cast_votes.success = false\n"
" AND bdr_sequence_values.seqschema = cast_votes.seqschema\n"
" AND bdr_sequence_values.seqname = cast_votes.seqname\n"
" AND bdr_sequence_values.seqrange = cast_votes.seqrange\n"
" AND bdr_sequence_values.owning_sysid = $1\n"
" AND bdr_sequence_values.owning_tlid = $2\n"
" AND bdr_sequence_values.owning_dboid = $3\n"
" AND bdr_sequence_values.owning_riname = $4\n"
" RETURNING bdr_sequence_values.*\n"
")\n"
"\n"
"SELECT\n"
" seqschema,\n"
" seqname,\n"
" seqrange,\n"
" 'success'::text\n"
"FROM successfull_sequence_values\n"
"\n"
"UNION ALL\n"
"\n"
"SELECT\n"
" seqschema,\n"
" seqname,\n"
" seqrange,\n"
" 'failed'::text\n"
"FROM failed_sequence_values\n"
"\n"
"UNION ALL\n"
"\n"
"SELECT\n"
" seqschema,\n"
" seqname,\n"
" seqrange,\n"
" 'pending'::text\n"
"FROM tallied_votes\n"
"WHERE NOT sufficient\n"
;
const char *fill_sequences_sql =
"SELECT\n"
" pg_class.oid seqoid,\n"
" pg_namespace.nspname seqschema,\n"
" pg_class.relname seqname\n"
"FROM pg_class\n"
" JOIN pg_seqam ON (pg_seqam.oid = pg_class.relam)\n"
" JOIN pg_namespace ON (pg_class.relnamespace = pg_namespace.oid)\n"
"WHERE\n"
" relkind = 'S'\n"
" AND seqamname = 'bdr'\n"
"ORDER BY pg_class.oid\n"
;
const char *get_chunk_sql =
"UPDATE bdr_sequence_values\n"
" SET in_use = true\n"
"WHERE\n"
" (\n"
" owning_sysid,\n"
" owning_tlid,\n"
" owning_dboid,\n"
" owning_riname,\n"
" seqname,\n"
" seqschema,\n"
" seqrange\n"
" )\n"
" =\n"
" (\n"
" SELECT\n"
" newval.owning_sysid,\n"
" newval.owning_tlid,\n"
" newval.owning_dboid,\n"
" newval.owning_riname,\n"
" newval.seqname,\n"
" newval.seqschema,\n"
" newval.seqrange\n"
" FROM bdr_sequence_values newval\n"
" WHERE\n"
" newval.confirmed\n"
" AND NOT newval.emptied\n"
" AND NOT newval.in_use\n"
" AND newval.owning_sysid = $1\n"
" AND newval.owning_tlid = $2\n"
" AND newval.owning_dboid = $3\n"
" AND newval.owning_riname = $4\n"
" AND newval.seqschema = $5\n"
" AND newval.seqname = $6\n"
" ORDER BY newval.seqrange ASC\n"
" LIMIT 1\n"
" FOR UPDATE\n"
" )\n"
"RETURNING\n"
" lower(seqrange),\n"
" upper(seqrange)\n"
;
static Size
bdr_sequencer_shmem_size(void)
{
Size size = 0;
size = add_size(size, sizeof(BdrSequencerControl));
size = add_size(size, mul_size(bdr_seq_nsequencers, sizeof(BdrSequencerSlot)));
return size;
}
static void
bdr_sequencer_shmem_shutdown(int code, Datum arg)
{
BdrSequencerSlot *slot;
if (seq_slot < 0)
return;
Assert(seq_slot < bdr_seq_nsequencers);
slot = &BdrSequencerCtl->slots[seq_slot];
slot->database_oid = InvalidOid;
slot->proclatch = NULL;
seq_slot = -1;
}
static void
bdr_sequencer_shmem_startup(void)
{
bool found;
if (prev_shmem_startup_hook != NULL)
prev_shmem_startup_hook();
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
BdrSequencerCtl = ShmemInitStruct("bdr_sequencer",
bdr_sequencer_shmem_size(),
&found);
if (!found)
{
/* initialize */
memset(BdrSequencerCtl, 0, bdr_sequencer_shmem_size());
/*
* next_slot allows perdb workers to allocate seq slots.
* The sequencer will likely be separated into a different
* worker later.
*/
BdrSequencerCtl->next_slot = 0;
}
LWLockRelease(AddinShmemInitLock);
on_shmem_exit(bdr_sequencer_shmem_shutdown, (Datum) 0);
}
void
bdr_sequencer_shmem_init(int sequencers)
{
Assert(process_shared_preload_libraries_in_progress);
bdr_seq_nsequencers = sequencers;
RequestAddinShmemSpace(bdr_sequencer_shmem_size());
prev_shmem_startup_hook = shmem_startup_hook;
shmem_startup_hook = bdr_sequencer_shmem_startup;
/*
* We do the reloptions initialization here because this function is called
* at startup for every backend.
*/
bdr_seq_relopt_kind = add_reloption_kind();
add_int_reloption(bdr_seq_relopt_kind, "cache_chunks",
"Sets how many chunks shoult be cached on each node.",
5, 5, 100);
}
/*
* The perdb worker doing sequencer setup needs to know what slot to
* allocate for the next sequencer.
*
* This should go away once the sequencer is separated into its own
* worker.
*/
int
bdr_sequencer_get_next_free_slot(void)
{
return BdrSequencerCtl->next_slot ++;
}
void
bdr_sequencer_wakeup(void)
{
size_t off;
BdrSequencerSlot *slot;
for (off = 0; off < bdr_seq_nsequencers; off++)
{
slot = &BdrSequencerCtl->slots[off];
/* FIXME: locking! */
if (slot->database_oid == InvalidOid)
continue;
if (slot->database_oid != MyDatabaseId)
continue;
SetLatch(slot->proclatch);
}
}
static void
bdr_sequence_xact_callback(XactEvent event, void *arg)
{
if (event != XACT_EVENT_COMMIT)
return;
if (bdr_seq_pending_wakeup)
{
bdr_sequencer_wakeup();
bdr_seq_pending_wakeup = false;
}
}
/*
* Schedule a wakeup of all sequencer workers, as soon as this transaction
* commits.
*
* This is e.g. useful when a new sequence is created, and the voting process
* should start immediately.
*
* NB: There's a window between the commit and this callback in which this
* backend could die without causing a cluster wide restart. So we need to
* periodically check whether we've missed wakeups.
*/
void
bdr_schedule_eoxact_sequencer_wakeup(void)
{
static bool registered = false;
if (!registered)
{
RegisterXactCallback(bdr_sequence_xact_callback, NULL);
registered = true;
}
bdr_seq_pending_wakeup = true;
}
void
bdr_sequencer_set_nnodes(int nnodes)
{
BdrSequencerSlot *slot = &BdrSequencerCtl->slots[seq_slot];
Assert(nnodes >= 0);
slot->nnodes = nnodes;
}
void
bdr_sequencer_init(int new_seq_slot, int nnodes)
{
BdrSequencerSlot *slot;
Assert(nnodes >= 0);
Assert(seq_slot == -1);
seq_slot = new_seq_slot;
slot = &BdrSequencerCtl->slots[seq_slot];
slot->database_oid = MyDatabaseId;
slot->proclatch = &MyProc->procLatch;
slot->nnodes = nnodes;
}
/*
* Acquire sequencer lock.
*
* We lock on on our seqam instead of the underlying relations. That's
* advantageous because we only want to prevent modifications by the sequencer
* or apply processes, it's perfectly fine for auto-analyze/vacuum to process
* the relation.
*/
void
bdr_sequencer_lock(void)
{
SetCurrentStatementStartTimestamp();
pgstat_report_activity(STATE_RUNNING, "acquiring sequencer lock");
LockDatabaseObject(SeqAccessMethodRelationId, BdrSeqamOid, InvalidOid,
ExclusiveLock);
}
bool
bdr_sequencer_vote(void)
{
static SPIPlanPtr plan;
Oid argtypes[4];
Datum values[4];
char nulls[4];
char local_sysid[32];
int ret;
int processed = 0;
snprintf(local_sysid, sizeof(local_sysid), UINT64_FORMAT,
GetSystemIdentifier());
argtypes[0] = TEXTOID;
nulls[0] = false;
values[0] = CStringGetTextDatum(local_sysid);
argtypes[1] = OIDOID;
nulls[1] = false;
values[1] = ObjectIdGetDatum(ThisTimeLineID);
argtypes[2] = OIDOID;
values[2] = ObjectIdGetDatum(MyDatabaseId);
nulls[2] = false;
argtypes[3] = TEXTOID;
values[3] = CStringGetTextDatum("");
nulls[3] = false;
StartTransactionCommand();
SPI_connect();
bdr_sequencer_lock();
PushActiveSnapshot(GetTransactionSnapshot());
if (plan == NULL)
{
plan = SPI_prepare(vote_sql, 4, argtypes);
SPI_keepplan(plan);
}
SetCurrentStatementStartTimestamp();
pgstat_report_activity(STATE_RUNNING, "sequence voting");
ret = SPI_execute_plan(plan, values, nulls, false, 0);
if (ret != SPI_OK_SELECT)
elog(ERROR, "expected SPI state %u, got %u", SPI_OK_INSERT, ret);
if (SPI_processed > 0)
{
HeapTuple tuple = SPI_tuptable->vals[0];
TupleDesc tupdesc = SPI_tuptable->tupdesc;
Datum inserted;
bool isnull;
inserted = SPI_getbinval(tuple, tupdesc, 1, &isnull);
Assert(!isnull);
processed = DatumGetInt32(inserted);
}
PopActiveSnapshot();
SPI_finish();
CommitTransactionCommand();
pgstat_report_stat(false);
elog(DEBUG1, "started %d votes", processed);
return processed > 0;
}
/*
* Check whether we need to initiate a voting procedure for getting new
* sequence chunks.
*/
bool
bdr_sequencer_start_elections(void)
{
static SPIPlanPtr plan;
Oid argtypes[4];
Datum values[4];
char nulls[4];
char local_sysid[32];
int ret;
int processed;
snprintf(local_sysid, sizeof(local_sysid), UINT64_FORMAT,
GetSystemIdentifier());
StartTransactionCommand();
SPI_connect();
argtypes[0] = TEXTOID;
nulls[0] = false;
values[0] = CStringGetTextDatum(local_sysid);
argtypes[1] = OIDOID;
nulls[1] = false;
values[1] = ObjectIdGetDatum(ThisTimeLineID);
argtypes[2] = OIDOID;
values[2] = ObjectIdGetDatum(MyDatabaseId);
nulls[2] = false;
argtypes[3] = TEXTOID;
values[3] = CStringGetTextDatum("");
nulls[3] = false;
bdr_sequencer_lock();
PushActiveSnapshot(GetTransactionSnapshot());
if (plan == NULL)
{
plan = SPI_prepare(start_elections_sql, 4, argtypes);
SPI_keepplan(plan);
}
SetCurrentStatementStartTimestamp();
pgstat_report_activity(STATE_RUNNING, "start_elections");
ret = SPI_execute_plan(plan, values, nulls, false, 0);
if (ret != SPI_OK_INSERT_RETURNING)
elog(ERROR, "expected SPI state %u, got %u", SPI_OK_INSERT_RETURNING, ret);
elog(DEBUG1, "started %d elections", SPI_processed);
processed = SPI_processed;
PopActiveSnapshot();
SPI_finish();
CommitTransactionCommand();
pgstat_report_stat(false);
return processed > 0;
}
/*
* Check whether enough votes have come in for any of *our* in progress
* elections.
*/
void
bdr_sequencer_tally(void)
{
static SPIPlanPtr plan;
Oid argtypes[5];
Datum values[5];
char nulls[5];
char local_sysid[32];
int ret;
snprintf(local_sysid, sizeof(local_sysid), UINT64_FORMAT,
GetSystemIdentifier());
StartTransactionCommand();
SPI_connect();
argtypes[0] = TEXTOID;
nulls[0] = false;
values[0] = CStringGetTextDatum(local_sysid);
argtypes[1] = OIDOID;
nulls[1] = false;
values[1] = ObjectIdGetDatum(ThisTimeLineID);
argtypes[2] = OIDOID;
values[2] = ObjectIdGetDatum(MyDatabaseId);
nulls[2] = false;
argtypes[3] = TEXTOID;
values[3] = CStringGetTextDatum("");
nulls[3] = false;
argtypes[4] = INT4OID;
values[4] = Int32GetDatum(BdrSequencerCtl->slots[seq_slot].nnodes);
nulls[4] = false;
bdr_sequencer_lock();
PushActiveSnapshot(GetTransactionSnapshot());
if (plan == NULL)
{
plan = SPI_prepare(tally_elections_sql, 5, argtypes);
SPI_keepplan(plan);
}
SetCurrentStatementStartTimestamp();
pgstat_report_activity(STATE_RUNNING, "tally_elections");
ret = SPI_execute_plan(plan, values, nulls, false, 0);
if (ret != SPI_OK_SELECT)
elog(ERROR, "expected SPI state %u, got %u", SPI_OK_SELECT, ret);
elog(DEBUG1, "tallied %d elections", SPI_processed);
PopActiveSnapshot();
SPI_finish();
CommitTransactionCommand();
pgstat_report_stat(false);
}
static int
bdr_sequence_value_cmp(const void *a, const void *b)
{
const BdrSequenceValues *left = a;
const BdrSequenceValues *right = b;
if (left->start_value < right->start_value)
return -1;
if (left->start_value == right->start_value)
return 0;
return 1;
}
/*
* Replace a single (uninitialized or used up) chunk by a free one. Mark the
* new chunk from bdr_sequence_values as in_use.
*
* Returns whether we could find a chunk or not.
*/
static bool
bdr_sequencer_fill_chunk(Oid seqoid, char *seqschema, char *seqname,
BdrSequenceValues *curval)
{
static SPIPlanPtr plan;
Oid argtypes[6];
Datum values[6];
char nulls[6];
char local_sysid[32];
int ret;
int64 lower, upper;
bool success;
SPI_push();
SPI_connect();
snprintf(local_sysid, sizeof(local_sysid), UINT64_FORMAT,
GetSystemIdentifier());
argtypes[0] = TEXTOID;
nulls[0] = false;
values[0] = CStringGetTextDatum(local_sysid);
argtypes[1] = OIDOID;
nulls[1] = false;
values[1] = ObjectIdGetDatum(ThisTimeLineID);
argtypes[2] = OIDOID;
values[2] = ObjectIdGetDatum(MyDatabaseId);
nulls[2] = false;
argtypes[3] = TEXTOID;
values[3] = CStringGetTextDatum("");
nulls[3] = false;
argtypes[4] = TEXTOID;
values[4] = CStringGetTextDatum(seqschema);
nulls[4] = false;
argtypes[5] = TEXTOID;
values[5] = CStringGetTextDatum(seqname);
nulls[5] = false;
SetCurrentStatementStartTimestamp();
pgstat_report_activity(STATE_RUNNING, "get_chunk");
if (plan == NULL)
{
plan = SPI_prepare(get_chunk_sql, 6, argtypes);
SPI_keepplan(plan);
}
ret = SPI_execute_plan(plan, values, nulls, false, 0);
if (ret != SPI_OK_UPDATE_RETURNING)
elog(ERROR, "expected SPI state %u, got %u", SPI_OK_UPDATE_RETURNING, ret);
if (SPI_processed != 1)
{
elog(DEBUG2, "no free chunks for sequence %s.%s",
seqschema, seqname);
success = false;
}
else
{
HeapTuple tup = SPI_tuptable->vals[0];
bool isnull;
lower = DatumGetInt64(SPI_getbinval(tup, SPI_tuptable->tupdesc, 1, &isnull));
Assert(!isnull);
upper = DatumGetInt64(SPI_getbinval(tup, SPI_tuptable->tupdesc, 2, &isnull));
Assert(!isnull);
elog(DEBUG2, "got chunk [%zu, %zu) for sequence %s.%s",
lower, upper, seqschema, seqname);
curval->start_value = lower;
curval->next_value = lower;
curval->end_value = upper;
success = true;
}
SPI_finish();
SPI_pop();
return success;
}
/*
* Search for used up chunks in one bdr sequence.
*/
static void
bdr_sequencer_fill_sequence(Oid seqoid, char *seqschema, char *seqname)
{
Buffer buf;
SeqTable elm;
Relation rel;
HeapTupleData seqtuple;
Datum values[SEQ_COL_LASTCOL];
bool nulls[SEQ_COL_LASTCOL];
HeapTuple newtup;
Page page, temppage;
BdrSequenceValues *curval, *firstval;
int i;
bool acquired_new = false;
LockRelId heaprelid;
LOCKTAG heaplocktag;
VirtualTransactionId *lockholders;
/* lock page, fill heaptup */
init_sequence(seqoid, &elm, &rel);
(void) read_seq_tuple(elm, rel, &buf, &seqtuple);
/* get values */
heap_deform_tuple(&seqtuple, RelationGetDescr(rel),
values, nulls);
/* now make sure we have space for our own data */
if (nulls[SEQ_COL_AMDATA - 1])
{
struct varlena *vl = palloc0(VARHDRSZ + sizeof(BdrSequenceValues) * 10);
SET_VARSIZE(vl, VARHDRSZ + sizeof(BdrSequenceValues) * 10);
nulls[SEQ_COL_AMDATA - 1] = false;
values[SEQ_COL_AMDATA - 1] = PointerGetDatum(vl);
}
firstval = (BdrSequenceValues *)
VARDATA_ANY(DatumGetByteaP(values[SEQ_COL_AMDATA - 1]));
curval = firstval;
for (i = 0; i < 10; i ++)
{
if (curval->next_value == curval->end_value)
{
if (curval->end_value > 0)
elog(DEBUG1, "sequence %s.%s: used up old chunk",
seqschema, seqname);
elog(DEBUG2, "sequence %s.%s: needs new batch %i",
seqschema, seqname, i);
if (bdr_sequencer_fill_chunk(seqoid, seqschema, seqname, curval))
acquired_new = true;
else
break;
}
curval++;
}
if (!acquired_new)
goto done_with_sequence;
/* sort chunks, so we always use the smallest one first */
qsort(firstval, 10, sizeof(BdrSequenceValues), bdr_sequence_value_cmp);
newtup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
/* special requirements for sequence tuples */
HeapTupleHeaderSetXmin(newtup->t_data, FrozenTransactionId);
HeapTupleHeaderSetXminFrozen(newtup->t_data);
HeapTupleHeaderSetCmin(newtup->t_data, FirstCommandId);
HeapTupleHeaderSetXmax(newtup->t_data, InvalidTransactionId);
newtup->t_data->t_infomask |= HEAP_XMAX_INVALID;
ItemPointerSet(&newtup->t_data->t_ctid, 0, FirstOffsetNumber);
page = BufferGetPage(buf);
temppage = PageGetTempPage(page);
/* replace page contents, the direct way */
PageInit(temppage, BufferGetPageSize(buf), PageGetSpecialSize(page));
memcpy(PageGetSpecialPointer(temppage),
PageGetSpecialPointer(page),
PageGetSpecialSize(page));
if (PageAddItem(temppage, (Item) newtup->t_data, newtup->t_len,
FirstOffsetNumber, false, false) == InvalidOffsetNumber)
elog(PANIC, "fill_sequence: failed to add item to page");
PageSetLSN(temppage, PageGetLSN(page));
START_CRIT_SECTION();
MarkBufferDirty(buf);