-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathstate.c
4450 lines (3926 loc) · 136 KB
/
state.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
/*-----------------------------------------------------------------------------
* state.c
*
* Copyright (c) 2017-2020, Postgres Professional
*
*-----------------------------------------------------------------------------
*/
#include "postgres.h"
/* mkdir, read/write */
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "access/twophase.h"
#include "access/xlogutils.h"
#include "access/xlog_internal.h"
#include "executor/spi.h"
#include "utils/snapmgr.h"
#include "nodes/makefuncs.h"
#include "catalog/namespace.h"
#include "catalog/pg_type.h"
#include "tcop/tcopprot.h"
#include "pgstat.h"
#include "port/pg_crc32c.h"
#include "storage/ipc.h"
#include "miscadmin.h" /* PostmasterPid */
#include "utils/syscache.h"
#include "utils/inval.h"
#include "replication/slot.h"
#include "replication/origin.h"
#include "miscadmin.h"
#include "postmaster/interrupt.h"
#include "replication/logical.h"
#include "replication/message.h"
#include "utils/builtins.h"
#include "funcapi.h"
#include "libpq/pqformat.h"
#include "multimaster.h"
#include "bkb.h"
#include "commit.h"
#include "ddl.h"
#include "state.h"
#include "syncpoint.h"
#include "logger.h"
#include "messaging.h"
char const *const MtmNeighborEventMnem[] =
{
"MTM_NEIGHBOR_CLIQUE_DISABLE",
"MTM_NEIGHBOR_WAL_RECEIVER_START",
"MTM_NEIGHBOR_WAL_RECEIVER_ERROR",
"MTM_NEIGHBOR_WAL_SENDER_START_RECOVERY",
"MTM_NEIGHBOR_WAL_SENDER_START_RECOVERED",
"MTM_NEIGHBOR_RECOVERY_CAUGHTUP",
"MTM_NEIGHBOR_WAL_SENDER_STOP"
};
char const *const MtmEventMnem[] =
{
"MTM_REMOTE_DISABLE",
"MTM_CLIQUE_DISABLE",
"MTM_CLIQUE_MINORITY",
"MTM_ARBITER_RECEIVER_START",
"MTM_RECOVERY_START1",
"MTM_RECOVERY_START2",
"MTM_RECOVERY_FINISH1",
"MTM_RECOVERY_FINISH2",
"MTM_NONRECOVERABLE_ERROR"
};
char const *const MtmNodeStatusMnem[] =
{
"isolated",
"disabled",
"catchup",
"recovery",
"online"
};
static char const *const MtmStatusInGenMnem[] =
{
"dead",
"recovery",
"online"
};
struct MtmState
{
/*
* Persistent state.
*
* My current generation, never goes backwards.
* (this is not MtmGeneration because atomic provides fast path in
* MtmConsiderGenSwitch)
*/
pg_atomic_uint64 current_gen_num;
nodemask_t current_gen_members;
nodemask_t current_gen_configured;
/*
* subset of current_gen_members which definitely has all xacts of gens
* < current_gen.num; always has at least one node. From these nodes we
* can recover to participate in this gen.
*/
nodemask_t donors;
/*
* Last generation I was online in. Must be persisted to disk before
* updating current_gen; used for determining donors who definitely hold
* all possibly committed prepares of previous gens.
*/
uint64 last_online_in;
/*
* Oldest gen for which we I have voted.
* Used for not voting twice and to keep the promise 'once we voted for n,
* don't update last_online_in to any num < n', which allows to learn
* who are donors during the voting.
*/
MtmGeneration last_vote;
/*
* When getting online we must 1) update state file 2) log message to WAL,
* apply.c relies on that. This flag makes sure both actions are done.
*/
bool ps_logged;
/* Guards generation switch */
LWLock *gen_lock;
/*
* However, gen switcher must also take this barrier as keeping LWLock
* during PREPARE is not nice.
*/
slock_t cb_lock;
int n_apply_preparers;
int n_backend_preparers;
int n_backend_holders;
int n_full_holders;
ConditionVariable commit_barrier_cv;
/*
* Voters exclude each other and gen switch, but don't change current gen
* and thus allow (e.g. heartbeat sender) to peek it, hence the second
* lock protecting last_vote.
*/
LWLock *vote_lock;
/*
* Last generation where each other node was online, collected via
* heartbeats. Used to determine donor during catchup, when others
* don't wait for us yet but we decrease the lag.
*
* Each element is updated only by the corresponding dmq receiver, so
* use atomics instead of adding locking.
*/
pg_atomic_uint64 others_last_online_in[MTM_MAX_NODES];
/*
* Connectivity state, maintained by dmq.
* dmq_* masks don't contain myself; MtmGetConnectedMaskWithMe handles that.
*/
nodemask_t dmq_receivers_mask;
nodemask_t dmq_senders_mask;
/* Whom others see to the best of our knowledge */
nodemask_t connectivity_matrix[MTM_MAX_NODES];
/* Protects the whole connectivity state. Make it spinlock? */
LWLock *connectivity_lock;
/*
* Direction to receivers how they should work:
* RECEIVE_MODE_NORMAL or RECEIVE_MODE_DISABLED or donor node id.
* Modifications are protected by excl gen_lock or shared vote_lock + excl
* vote_lock.
*/
pg_atomic_uint32 receive_mode;
pid_t campaigner_pid;
bool campaigner_on_tour; /* protected by vote_lock */
/* receiver reports its progress in recovery here */
int catchup_node_id;
instr_time catchup_ts;
slock_t catchup_lock;
/*
* Attempt to clear the referee grant until it succeeds.
* This could be bool except the paranoia in RefereeClearGrant.
*/
uint64 referee_grant_turn_in_pending;
/*
* making current code compilable while I haven't fixed up things
*/
LWLock *lock;
nodemask_t connected_mask;
nodemask_t receivers_mask;
nodemask_t senders_mask;
nodemask_t enabled_mask;
nodemask_t clique;
nodemask_t configured_mask;
bool referee_grant;
int referee_winner_id;
bool recovered;
int recovery_slot;
MtmNodeStatus status;
} *mtm_state;
static void CampaignerWake(void);
static void MtmSetReceiveMode(uint32 mode);
static XLogRecPtr LogParallelSafe(MtmGeneration gen, nodemask_t donors);
static bool MtmIsConnectivityClique(nodemask_t mask);
static nodemask_t MtmGetConnectivityClique(bool locked);
/* serialization functions */
static void MtmStateSave(void);
static void MtmStateLoad(void);
static void GetLoggedPreparedXactState(HTAB *txset);
PG_FUNCTION_INFO_V1(mtm_node_info);
PG_FUNCTION_INFO_V1(mtm_status);
PG_FUNCTION_INFO_V1(mtm_state_create);
PG_FUNCTION_INFO_V1(mtm_get_logged_prepared_xact_state);
static bool pb_hook_registred = false;
/* Variation of acquired prepare barrier. */
typedef enum
{
PB_NONE,
PB_APPLY_PREPARER, /* applier who prepares */
PB_BACKEND_PREPARER, /* backend who prepares */
PB_BACKEND_HOLDER, /* blocks only backends from preparing */
PB_FULL_HOLDER, /* blocks everyone from preparing */
} PrepareBarrierMode;
static PrepareBarrierMode pb_acquired_in_mode;
static bool campaign_requested;
/*
* -----------------------------------
* Startup
* -----------------------------------
*/
void
MtmStateInit()
{
RequestAddinShmemSpace(sizeof(struct MtmState));
RequestNamedLWLockTranche("mtm_state_locks", 3);
}
void
MtmStateShmemStartup()
{
bool found;
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
mtm_state = ShmemInitStruct("mtm_state", sizeof(struct MtmState), &found);
if (!found)
{
int i;
MemSet(mtm_state, '\0', sizeof(struct MtmState));
mtm_state->gen_lock = &(GetNamedLWLockTranche("mtm_state_locks")[0].lock);
mtm_state->connectivity_lock = &(GetNamedLWLockTranche("mtm_state_locks")[1].lock);
mtm_state->vote_lock = &(GetNamedLWLockTranche("mtm_state_locks")[2].lock);
pg_atomic_init_u64(&mtm_state->current_gen_num, MtmInvalidGenNum);
for (i = 0; i < MTM_MAX_NODES; i++)
{
pg_atomic_init_u64(&mtm_state->others_last_online_in[i], MtmInvalidGenNum);
}
SpinLockInit(&mtm_state->cb_lock);
ConditionVariableInit(&mtm_state->commit_barrier_cv);
pg_atomic_init_u32(&mtm_state->receive_mode, RECEIVE_MODE_DISABLED);
SpinLockInit(&mtm_state->catchup_lock);
mtm_state->catchup_node_id = MtmInvalidNodeId;
}
LWLockRelease(AddinShmemInitLock);
}
/*
* State initialization called by monitor. It is problematic to do this
* earlier (at shmem_startup_hook) as we need our Mtm->my_node_id which is
* fetched from table and set in shmem by monitor.
*/
void
MtmStateStartup(void)
{
AcquirePBByHolder(true);
LWLockAcquire(mtm_state->gen_lock, LW_EXCLUSIVE);
MtmStateLoad();
/* restore receive_mode */
switch (MtmGetCurrentStatusInGen())
{
case MTM_GEN_ONLINE:
pg_atomic_write_u32(&mtm_state->receive_mode, RECEIVE_MODE_NORMAL);
break;
case MTM_GEN_RECOVERY:
{
int donor = first_set_bit(mtm_state->donors) + 1;
Assert(donor > 0);
pg_atomic_write_u32(&mtm_state->receive_mode, donor);
break;
}
case MTM_GEN_DEAD:
pg_atomic_write_u32(&mtm_state->receive_mode, RECEIVE_MODE_DISABLED);
break;
}
/*
* if we crashed after file update to online but before logging PS,
* do it now
*/
if ((MtmGetCurrentGenNum() == mtm_state->last_online_in) &&
(!mtm_state->ps_logged))
{
LogParallelSafe(MtmGetCurrentGen(true), mtm_state->donors);
mtm_state->ps_logged = true;
MtmStateSave();
}
LWLockRelease(mtm_state->gen_lock);
ReleasePB();
}
/* Create persistent state during cluster initialization */
Datum
mtm_state_create(PG_FUNCTION_ARGS)
{
/*
* Initial node ids normally are 1..n_nodes, but we pass array of node ids
* here to allow tests configure sparse numbers.
*/
ArrayType *node_ids_arr = PG_GETARG_ARRAYTYPE_P(0);
Datum *node_ids_datums;
bool *node_ids_nulls;
int n_nodes;
int i;
/* parse array with node ids */
Assert(ARR_ELEMTYPE(node_ids_arr) == INT4OID);
Assert(ARR_NDIM(node_ids_arr) == 1);
deconstruct_array(node_ids_arr,
INT4OID,
4, true, 'i',
&node_ids_datums, &node_ids_nulls, &n_nodes);
/*
* Initially, all members are online in gen 1.
* Nobody should be messing up with mtm_state at this point, but just in
* case (e.g. previous cluster?), take lock.
*/
LWLockAcquire(mtm_state->gen_lock, LW_EXCLUSIVE);
pg_atomic_write_u64(&mtm_state->current_gen_num, 1);
mtm_state->current_gen_members = 0;
mtm_state->current_gen_configured = 0;
for (i = 0; i < n_nodes; i++)
{
int node_id = DatumGetInt32(node_ids_datums[i]);
Assert(node_id >= 1);
BIT_SET(mtm_state->current_gen_members, node_id - 1);
BIT_SET(mtm_state->current_gen_configured, node_id - 1);
}
mtm_state->donors = mtm_state->current_gen_members;
mtm_state->last_online_in = 1;
mtm_state->last_vote = ((MtmGeneration) {1, mtm_state->current_gen_members});
MtmStateSave();
/*
* zero out gen num again: we are not ready until monitor hasn't done
* MtmStateStartup, re-reading it from disk
*/
pg_atomic_write_u64(&mtm_state->current_gen_num, MtmInvalidNodeId);
LWLockRelease(mtm_state->gen_lock);
PG_RETURN_VOID();
}
/*
* -----------------------------------
* Generation management
* -----------------------------------
*/
uint64
MtmGetCurrentGenNum(void)
{
return pg_atomic_read_u64(&mtm_state->current_gen_num);
}
MtmGeneration
MtmGetCurrentGen(bool locked)
{
MtmGeneration res;
if (!locked)
LWLockAcquire(mtm_state->gen_lock, LW_SHARED);
Assert(LWLockHeldByMe(mtm_state->gen_lock) || pb_acquired_in_mode);
res = (MtmGeneration)
{
.num = pg_atomic_read_u64(&mtm_state->current_gen_num),
.members = mtm_state->current_gen_members,
.configured = mtm_state->current_gen_configured
};
if (!locked)
LWLockRelease(mtm_state->gen_lock);
return res;
}
/* TODO: make messaging layer for logical messages like existing dmq one */
static void
PackGenAndDonors(StringInfo s, MtmGeneration gen, nodemask_t donors)
{
initStringInfo(s);
pq_sendint64(s, gen.num);
pq_sendint64(s, gen.members);
pq_sendint64(s, gen.configured);
pq_sendint64(s, donors);
}
static XLogRecPtr
LogParallelSafe(MtmGeneration gen, nodemask_t donors)
{
StringInfoData s;
XLogRecPtr msg_xptr;
PackGenAndDonors(&s, gen, donors);
/* xxx we should add versioning to logical messages */
msg_xptr = LogLogicalMessage("P", s.data, s.len, false);
pfree(s.data);
XLogFlush(msg_xptr);
return msg_xptr;
}
/* Switch into newer generation, if not yet */
void
MtmConsiderGenSwitch(MtmGeneration gen, nodemask_t donors)
{
/* generations with the same number must be the identic */
#ifdef USE_ASSERT_CHECKING
LWLockAcquire(mtm_state->gen_lock, LW_SHARED);
if (pg_atomic_read_u64(&mtm_state->current_gen_num) == gen.num)
{
Assert(mtm_state->current_gen_members == gen.members);
Assert(mtm_state->current_gen_configured == gen.configured);
}
LWLockRelease(mtm_state->gen_lock);
#endif
/* fast path executed normally */
if (likely(pg_atomic_read_u64(&mtm_state->current_gen_num) >= gen.num))
return;
/*
* Ok, most probably the switch is going to happen.
*
* Exclude all concurrent PREPAREs.
* Barrier between stopping applying/creating prepares from old gen and
* starting writing new gen prepares, embodied by
* ParallelSafe<gen> record, is crucial; once any new gen PREPARE appeared
* in WAL, accepting old one must be forbidden because recovery up to
* ParallelSafe (or any prepare from new gen) is a criterion that we have
* recovered to participate in this gen and thus got all committable xacts
* of older gens: receivers enter normal mode (pulling only origin's
* xacts) at this spot with usual dangers of out-of-order apply.
*
* Backends don't use gen_lock for that though because
* - Doing PrepareTransactionBlock/CommitTransactionCommand under lwlock
* is formidable.
* - lwlocks are unfair.
* XXX these arguments seem somewhat weak. The first should be
* investigated and the second can be hacked around with sleep request.
*
* LWlock puts us into uninterrutable sleep, so better take PB first.
*/
AcquirePBByHolder(true);
LWLockAcquire(mtm_state->gen_lock, LW_EXCLUSIVE);
/*
* Doesn't happen normally, this means dmq receiver appeared earlier than
* monitor started. Should handle this nicer.
*/
if (pg_atomic_read_u64(&mtm_state->current_gen_num) == MtmInvalidGenNum)
elog(ERROR, "multimaster is not initialized yet");
/* check once again under lock */
if (pg_atomic_read_u64(&mtm_state->current_gen_num) >= gen.num)
{
ReleasePB();
LWLockRelease(mtm_state->gen_lock);
return;
}
/* voting for generation n <= m is pointless if gen m was already elected */
if (mtm_state->last_vote.num < gen.num)
mtm_state->last_vote = gen; /* will be fsynced below along with rest of state */
/* update current gen */
pg_atomic_write_u64(&mtm_state->current_gen_num, gen.num);
mtm_state->current_gen_members = gen.members;
mtm_state->current_gen_configured = gen.configured;
mtm_state->donors = donors;
/*
* xxx SetLatch of all backends here? Waiting for acks after gen switch
* might be hopeless. Currently backends check for it after timeout...
*/
/* Probably we are not member of this generation... */
if (!BIT_CHECK(gen.members, Mtm->my_node_id - 1) ||
/*
* .. or gen doesn't have quorum by design, nor this is a referee
* granted gen where quorum is not required
*/
(!Quorum(popcount(gen.configured), popcount(gen.members)) &&
!IS_REFEREE_GEN(gen.members, gen.configured)) ||
/*
* .. or we have voted for greater last_vote.num, which means we've
* promised that the highest gen among gens with num < last_vote.num
* in which we ever can be online (and thus create xacts) is
* last_online_in on the moment of voting. To keep that promise,
* prevent getting ONLINE in gens with < last_vote.num numbers.
*/
mtm_state->last_vote.num > gen.num)
{
/*
* Then we can never create xacts in this gen. Shut down receivers
* and nudge campaigner to recover.
*/
MtmSetReceiveMode(RECEIVE_MODE_DISABLED);
MtmStateSave();
mtm_log(MtmStateSwitch, "[STATE] switched to dead in generation num=" UINT64_FORMAT ", members=%s, donors=%s, last_vote.num=" UINT64_FORMAT,
gen.num,
maskToString(gen.members),
maskToString(donors),
mtm_state->last_vote.num);
LWLockRelease(mtm_state->gen_lock);
ReleasePB();
CampaignerWake();
return;
}
/*
* Decide whether we need to recover in this generation or not.
*/
if (BIT_CHECK(donors, Mtm->my_node_id - 1))
{
XLogRecPtr msg_xptr;
/* no need to recover, we already have all xacts of lower gens */
mtm_state->ps_logged = false;
mtm_state->last_online_in = gen.num;
MtmStateSave(); /* fsync state update */
/*
* Write to WAL ParallelSafe<gen_num> message, which is a mark for
* those who will recover from us in this generation that they are
* recovered: all following xacts can't commit without approval of all
* new gen members, all committed xacts of previous generations lie
* before ParallelSafe.
* Note that any PREPARE from new gen could do this job as
* well if we carried full gen info with it; but this
* guarantees convergence in the absence of xacts.
*/
msg_xptr = LogParallelSafe(gen, donors);
mtm_state->ps_logged = true;
MtmStateSave(); /* fsync state update */
MtmSetReceiveMode(RECEIVE_MODE_NORMAL);
mtm_log(MtmStateSwitch, "[STATE] switched to online in generation num=" UINT64_FORMAT ", members=%s, donors=%s as donor, ParallelSafe logged at %X/%X",
gen.num,
maskToString(gen.members),
maskToString(donors),
(uint32) (msg_xptr >> 32), (uint32) msg_xptr);
}
else
{
/*
* Need recovery -- use random donor for that.
*/
int donor;
MtmStateSave(); /* fsync state update */
donor = first_set_bit(donors) + 1;
Assert(donor > 0);
MtmSetReceiveMode(donor);
mtm_log(MtmStateSwitch, "[STATE] switched to recovery in generation num=" UINT64_FORMAT ", members=%s, donors=%s, donor=%d",
gen.num,
maskToString(gen.members),
maskToString(donors),
donor);
}
LWLockRelease(mtm_state->gen_lock);
ReleasePB();
}
/*
* Handle ParallelSafe arrived to receiver. Getting it in recovery mode means
* we made all prepares of previous gens and can safely switch to
* MTM_GEN_ONLINE.
*
* Note that we don't relog the message. It's fine because 1) P.S. is
* idempotent, i.e. getting it twice is ok. We must process it at least once
* though. 2) Nodes interested in these records will eventually learn 'donors'
* who logged it and receive P.S. directly from one of them (unless yet
* another gen switch happened). So, forwarding it wouldn't harm safety, but
* there is no need in it.
*
* Returns true if the record can't be applied due to wrong receiver mode.
*/
bool
MtmHandleParallelSafe(MtmGeneration ps_gen, nodemask_t ps_donors,
bool is_recovery, XLogRecPtr end_lsn)
{
/*
* In MtmConsiderGenSwitch (and below) we might log ParallelSafe. Ensure
* it is originated by *us* so anyone pulling from us sees the gen switch
* before new gen xacts regardless of his apply mode; this makes it
* impossible to receive PREPARE in wrong mode or CP before P, see theirs
* apply comments.
*/
MtmEndSession(42, false);
/* make sure we are at least in ParallelSafe's gen */
MtmConsiderGenSwitch(ps_gen, ps_donors);
/* definitely not interested in this P.S. if we are already in higher gen */
if (ps_gen.num < MtmGetCurrentGenNum())
return false;
/*
* Ok, grab the excl lock as we are going to need it if P.S. will actually
* make us ONLINE. We could do unlocked check whether we are already
* online, but performance here doesn't matter as P.S. is logged only
* on live nodes / networking changes.
*/
LWLockAcquire(mtm_state->gen_lock, LW_EXCLUSIVE);
AcquirePBByHolder(true);
/*
* Not interested in this P.S. if we are in newer gen. Otherwise, still
* not interested if we are already ONLINE in this one or can never be
* online in it (due to promise or just not being a member).
*/
if (ps_gen.num != MtmGetCurrentGenNum() ||
MtmGetCurrentStatusInGen() != MTM_GEN_RECOVERY)
{
ReleasePB();
LWLockRelease(mtm_state->gen_lock);
return false;
}
/*
* Catching P.S. in normal mode and promoting to ONLINE is not allowed; we
* probably just have given out all prepares before it to parallel workers
* without applying them. Reconnect in recovery.
*/
if (!is_recovery)
{
ReleasePB();
LWLockRelease(mtm_state->gen_lock);
return true;
}
/*
* Ok, so this parallel safe indeed switches us into ONLINE.
*
* Though we are definitely not donor and thus we expect nobody will
* recover from us in this gen, log ParallelSafe anyway to ensure the mark
* symbolizing switch into online-in-gen is always present in
* WAL. Applying PREPARE and especially COMMIT PREPARED (to prevent
* out-of-order CP apply) rely on this.
*/
mtm_state->ps_logged = false;
mtm_state->last_online_in = ps_gen.num;
MtmStateSave();
LogParallelSafe(ps_gen, ps_donors);
mtm_state->ps_logged = true;
MtmStateSave();
MtmSetReceiveMode(RECEIVE_MODE_NORMAL);
if (IS_REFEREE_ENABLED() && popcount(ps_gen.configured) == 2)
{
/*
* In referee mode we may switch to online by applying P.S. only in
* full generation; referee winner doesn't need recovery and switches
* to online directly in MtmConsiderGenSwitch in both referee gen and
* the following full gen.
*/
Assert(popcount(ps_gen.members) == 2);
/*
* Now that both nodes are online we can clear the grant.
*/
mtm_state->referee_grant_turn_in_pending = ps_gen.num;
}
mtm_log(MtmStateSwitch, "[STATE] switched to online in generation num=" UINT64_FORMAT ", members=%s, donors=%s by applying ParallelSafe logged at %X/%X",
ps_gen.num,
maskToString(ps_gen.members),
maskToString(ps_donors),
(uint32) (end_lsn >> 32), (uint32) end_lsn);
ReleasePB();
LWLockRelease(mtm_state->gen_lock);
return false;
}
/*
* Node status in current generation. Closely follows MtmConsiderGenSwitch logic.
*/
MtmStatusInGen
MtmGetCurrentStatusInGen(void)
{
int me = Mtm->my_node_id;
uint64 current_gen_num;
if (me == MtmInvalidNodeId)
elog(ERROR, "multimaster is not configured");
Assert(LWLockHeldByMe(mtm_state->gen_lock) || pb_acquired_in_mode);
/*
* If we care about MTM_GEN_DEAD/MTM_GEN_RECOVERY distinction, should also
* keep either vote_lock or excl gen_lock, but some callers don't, so no
* assertion.
*/
current_gen_num = pg_atomic_read_u64(&mtm_state->current_gen_num);
if (current_gen_num == MtmInvalidGenNum)
elog(ERROR, "multimaster is not initialized yet");
if (mtm_state->last_online_in == current_gen_num)
return MTM_GEN_ONLINE; /* ready to do xacts */
/*
* We can hope to get eventually ONLINE in current generation iff we are
* member of it, its members form quorum and voting promises don't forbid
* us that.
*/
else if (BIT_CHECK(mtm_state->current_gen_members, me - 1) &&
Quorum(popcount(mtm_state->current_gen_configured),
popcount(mtm_state->current_gen_members)) &&
pg_atomic_read_u64(&mtm_state->current_gen_num) == mtm_state->last_vote.num)
return MTM_GEN_RECOVERY;
else
return MTM_GEN_DEAD; /* can't ever be online there */
}
/* most callers held lock, hence the second func instead of arg */
MtmStatusInGen
MtmGetCurrentStatusInGenNotLocked(void)
{
MtmStatusInGen res;
LWLockAcquire(mtm_state->gen_lock, LW_SHARED);
res = MtmGetCurrentStatusInGen();
LWLockRelease(mtm_state->gen_lock);
return res;
}
/*
* Mtm current status accessor for user facing code. Augments
* MtmGetCurrentStatusInGen with connectivity state: see, even if we are
* online in current gen, immediately telling user that node is online might
* be disappointing as e.g. we could instantly lost connection with all other
* nodes without learning about generation excluding us.
*
* Additionally distinguishes between 'need recovery, but have no idea from
* whom' and 'recovering from some node'.
*/
MtmNodeStatus
MtmGetCurrentStatus(bool gen_locked, bool vote_locked)
{
MtmStatusInGen status_in_gen;
MtmNodeStatus res;
/* doesn't impress with elegance, really */
if (!gen_locked)
LWLockAcquire(mtm_state->gen_lock, LW_SHARED);
if (!vote_locked)
LWLockAcquire(mtm_state->vote_lock, LW_SHARED);
Assert(LWLockHeldByMe(mtm_state->gen_lock) || pb_acquired_in_mode);
Assert(LWLockHeldByMe(mtm_state->vote_lock) ||
LWLockHeldByMeInMode(mtm_state->gen_lock, LW_EXCLUSIVE));
status_in_gen = MtmGetCurrentStatusInGen();
if (status_in_gen == MTM_GEN_DEAD)
{
if (pg_atomic_read_u32(&mtm_state->receive_mode) == RECEIVE_MODE_DISABLED)
res = MTM_DISABLED;
else
res = MTM_CATCHUP;
}
else
{
/*
* Our generation is viable, but check whether we see all its
* members. This is a subtle thing, probably deserving an improvement.
*
* The goal here is the following: if we are MTM_GEN_ONLINE in curr
* gen, connectivity for it is ok during this check and stays so
* hereafter, we shouldn't ERROR out later due to generation switches.
* Simply speaking, if you got success for "select 't'" from all nodes
* and no network/nodes failures happen, you obviously expect things
* to work.
*
* The first thing to ensure is that connectivity clique includes all
* current gen members. If it doesn't, campaigner will try to re-elect
* the generation. Note that simply checking connected mask is not
* enough; for instance, if during cluster boot node A (with gen ABC)
* sees B and C, but B <-> C don't see each other (or A is not aware
* of the connections yet), campaigner on 1 would try to exclude one
* of them. However, calculating clique on each xact start might be
* expensive; it is not hard to delegate this to dmq sender/receivers
* though -- TODO.
*
* Second, even if the connectivity right now is good, we must be sure
* campaigner doesn't operate an older data which might not be so
* good, lest he'd still attempt re-election. campaigner_on_tour
* serves this purpose.
*
* Now, since we don't attempt to poll other nodes here (and being
* cumbersome and expensive this is hardly worthwhile) we protect only
* from our campaigner reballoting if all goes well, but not the
* others, of course. e.g. races like
* - initially everyone in gen 1 <A, B, C>
* - A doesn't see B <-> C and successfully ballots for gen 2 <A, B>
* - "select 't'" gives ok at A and B
* - it also gives ok at C if C's clique is <A, B, C>, but C is not
* aware of gen 2's election at all.
* are still possible (and seen in practice). mtm_ping can be used to
* mitigate this if needed.
*
* Just in case, all this stuff doesn't influence safety; this is just
* a matter of deciding when to open the shop to the client.
*/
if (!is_submask(mtm_state->current_gen_members,
MtmGetConnectivityClique(false)) ||
mtm_state->campaigner_on_tour)
res = MTM_ISOLATED;
else if (status_in_gen == MTM_GEN_RECOVERY)
res = MTM_RECOVERY;
else
res = MTM_ONLINE;
}
if (!vote_locked)
LWLockRelease(mtm_state->vote_lock);
if (!gen_locked)
LWLockRelease(mtm_state->gen_lock);
return res;
}
/*
* The campaigner bgw, responsible for rising new generation elections.
*/
static void
CampaignerWake(void)
{
if (mtm_state->campaigner_pid != 0)
kill(mtm_state->campaigner_pid, SIGHUP);
}
/* campaigner never rereads PG config, but it currently it hardly needs to */
static void
CampaignerSigHupHandler(SIGNAL_ARGS)
{
int save_errno = errno;
campaign_requested = true;
SetLatch(MyLatch);
errno = save_errno;
}
static void
CampaignerOnExit(int code, Datum arg)
{
mtm_state->campaigner_pid = 0;
}
/* TODO: unite with resolver.c */
static void
scatter(MtmConfig *mtm_cfg, nodemask_t cmask, char *stream_name, StringInfo msg)
{
int i;
/*
* XXX: peeking Mtm->peers here is weird. e.g. nothing prevents rot of
* dest_id when dmq will actually send msg: we might send message to
* wrong node if node was removed and added in the middle. It is better
* to change dmq API to idenfity counterparties by user-supplied ints
* which can be mapped into internal dmq's handles for efficiency.
*
*/
for (i = 0; i < mtm_cfg->n_nodes; i++)
{
int node_id = mtm_cfg->nodes[i].node_id;
DmqDestinationId dest_id;
LWLockAcquire(Mtm->lock, LW_SHARED);
dest_id = Mtm->peers[node_id - 1].dmq_dest_id;
LWLockRelease(Mtm->lock);
if (dest_id >= 0 && BIT_CHECK(cmask, node_id - 1))
dmq_push_buffer(dest_id, stream_name, msg->data, msg->len);
}
}
/* report that receiver had caught up */
void
MtmReportReceiverCaughtup(int node_id)
{
instr_time cur_time;
INSTR_TIME_SET_CURRENT(cur_time);
SpinLockAcquire(&mtm_state->catchup_lock);
mtm_state->catchup_node_id = node_id;
mtm_state->catchup_ts = cur_time;
SpinLockRelease(&mtm_state->catchup_lock);
mtm_log(MtmStateMessage, "caughtup from node %d", node_id);
}
/*
* Set receive_mode to recover from random most advanced node (having greatest
* last_online_in) among given connected ones.
*/
static uint64
SetCatchupDonor(nodemask_t connected)
{
int i;
int most_advanced_node = MtmInvalidNodeId;
uint64 most_advanced_gen_num;
uint32 curr_receive_mode = pg_atomic_read_u32(&mtm_state->receive_mode);
most_advanced_gen_num = MtmInvalidGenNum;
for (i = 0; i < MTM_MAX_NODES; i++)
{
if (BIT_CHECK(connected, i))
{
uint64 gen_num = pg_atomic_read_u64(&mtm_state->others_last_online_in[i]);
if (gen_num > most_advanced_gen_num)
{
most_advanced_node = i + 1;
most_advanced_gen_num = gen_num;
}
}
}
/*
* If cluster has only one node, it can't be in MTM_GEN_DEAD and this
* function should never be called. If > 1 node, it ought to be called
* with majority of connected nodes, i.e. connected must have at least one
* node apart from me. (me has 0 value in others_last_online_in, it's
* quite useless though harmless to recover from myself)
*/
Assert(most_advanced_gen_num != MtmInvalidGenNum);
/*
* XXX: it is actually possible that *our* last_online_in is higher than
* most_advanced_gen_num, though we are in dead gen -- it means there are not
* enough recovered nodes around me, but someone caught up and elected
* minority gen, e.g.
* - 123 do a lot of xacts in gen n, 45 lag behind
* - now only 145 live, 45 catching up
* - 4 caught up and elected minority (dead) gen 14 with num n + 1.
* Here we still configure recovery from random node. This is harmless,
* but we could reflect this situation in monitoring better.
*/
/* Don't change donor unless we have a good reason to do that */
if (!IS_RECEIVE_MODE_DONOR(curr_receive_mode) ||
!BIT_CHECK(connected, curr_receive_mode - 1) ||
(pg_atomic_read_u64(&mtm_state->others_last_online_in[curr_receive_mode - 1]) <
most_advanced_gen_num))
{
MtmSetReceiveMode(most_advanced_node);
mtm_log(MtmStateSwitch, "set to catch up from node %d with max last_online_in=" UINT64_FORMAT " collected among connected=%s",
most_advanced_node,
most_advanced_gen_num,