-
Notifications
You must be signed in to change notification settings - Fork 108
/
node_active_protocol.c
2490 lines (2094 loc) · 71.7 KB
/
node_active_protocol.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
/*-------------------------------------------------------------------------
*
* src/monitor/node_active_protocol.c
*
* Implementation of the functions used to communicate with PostgreSQL
* nodes.
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the PostgreSQL License.
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "fmgr.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "access/xact.h"
#include "formation_metadata.h"
#include "group_state_machine.h"
#include "metadata.h"
#include "node_metadata.h"
#include "notifications.h"
#include "replication_state.h"
#include "access/htup_details.h"
#include "access/xlogdefs.h"
#include "catalog/pg_enum.h"
#include "nodes/makefuncs.h"
#include "nodes/parsenodes.h"
#include "parser/parse_type.h"
#include "storage/lockdefs.h"
#include "utils/builtins.h"
#include "utils/pg_lsn.h"
#include "utils/syscache.h"
/* private function forward declarations */
static AutoFailoverNodeState * NodeActive(char *formationId,
AutoFailoverNodeState *currentNodeState);
static void JoinAutoFailoverFormation(AutoFailoverFormation *formation,
char *nodeName, char *nodeHost, int nodePort,
uint64 sysIdentifier, char *nodeCluster,
AutoFailoverNodeState *currentNodeState);
static int AssignGroupId(AutoFailoverFormation *formation,
char *nodeHost, int nodePort,
ReplicationState *initialState);
static bool RemoveNode(AutoFailoverNode *currentNode, bool force);
/* SQL-callable function declarations */
PG_FUNCTION_INFO_V1(register_node);
PG_FUNCTION_INFO_V1(node_active);
PG_FUNCTION_INFO_V1(update_node_metadata);
PG_FUNCTION_INFO_V1(get_nodes);
PG_FUNCTION_INFO_V1(get_primary);
PG_FUNCTION_INFO_V1(get_other_node);
PG_FUNCTION_INFO_V1(get_other_nodes);
PG_FUNCTION_INFO_V1(remove_node);
PG_FUNCTION_INFO_V1(remove_node_by_nodeid);
PG_FUNCTION_INFO_V1(remove_node_by_host);
PG_FUNCTION_INFO_V1(perform_failover);
PG_FUNCTION_INFO_V1(perform_promotion);
PG_FUNCTION_INFO_V1(start_maintenance);
PG_FUNCTION_INFO_V1(stop_maintenance);
PG_FUNCTION_INFO_V1(set_node_candidate_priority);
PG_FUNCTION_INFO_V1(set_node_replication_quorum);
PG_FUNCTION_INFO_V1(synchronous_standby_names);
/*
* register_node adds a node to a given formation
*
* At register time the monitor connects to the node to check that nodehost and
* nodeport are valid, and it does a SELECT pg_is_in_recovery() to help decide
* what initial role to attribute the entering node.
*/
Datum
register_node(PG_FUNCTION_ARGS)
{
checkPgAutoFailoverVersion();
text *formationIdText = PG_GETARG_TEXT_P(0);
char *formationId = text_to_cstring(formationIdText);
text *nodeHostText = PG_GETARG_TEXT_P(1);
char *nodeHost = text_to_cstring(nodeHostText);
int32 nodePort = PG_GETARG_INT32(2);
Name dbnameName = PG_GETARG_NAME(3);
const char *expectedDBName = NameStr(*dbnameName);
text *nodeNameText = PG_GETARG_TEXT_P(4);
char *nodeName = text_to_cstring(nodeNameText);
uint64 sysIdentifier = PG_GETARG_INT64(5);
int64 currentNodeId = PG_GETARG_INT64(6);
int32 currentGroupId = PG_GETARG_INT32(7);
Oid currentReplicationStateOid = PG_GETARG_OID(8);
text *nodeKindText = PG_GETARG_TEXT_P(9);
char *nodeKind = text_to_cstring(nodeKindText);
FormationKind expectedFormationKind =
FormationKindFromNodeKindString(nodeKind);
int candidatePriority = PG_GETARG_INT32(10);
bool replicationQuorum = PG_GETARG_BOOL(11);
text *nodeClusterText = PG_GETARG_TEXT_P(12);
char *nodeCluster = text_to_cstring(nodeClusterText);
AutoFailoverNodeState currentNodeState = { 0 };
currentNodeState.nodeId = currentNodeId;
currentNodeState.groupId = currentGroupId;
currentNodeState.replicationState =
EnumGetReplicationState(currentReplicationStateOid);
currentNodeState.reportedLSN = 0;
currentNodeState.candidatePriority = candidatePriority;
currentNodeState.replicationQuorum = replicationQuorum;
LockFormation(formationId, ExclusiveLock);
AutoFailoverFormation *formation = GetFormation(formationId);
/*
* The default formationId is "default" and of kind FORMATION_KIND_PGSQL.
* It might get used to manage a formation though. Check about that here,
* and when the first node registered is a Citus node, update the target
* formation to be of kind Citus, actually.
*/
if (formation == NULL)
{
ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("formation \"%s\" does not exist", formationId),
errhint("Use `pg_autoctl create formation` "
"to create the target formation first")));
}
if (formation->kind != expectedFormationKind)
{
List *allNodes = AllAutoFailoverNodes(formationId);
if (list_length(allNodes) == 0)
{
/* first node in the list, let's switch to citus */
SetFormationKind(formationId, expectedFormationKind);
formation->kind = expectedFormationKind;
}
else
{
ereport(ERROR,
(errmsg("node %s:%d of kind \"%s\" can not be registered in "
"formation \"%s\" of kind \"%s\"",
nodeHost, nodePort, nodeKind,
formationId,
FormationKindToString(formation->kind))));
}
}
if (strncmp(formation->dbname, expectedDBName, NAMEDATALEN) != 0)
{
List *allNodes = AllAutoFailoverNodes(formationId);
if (list_length(allNodes) == 0)
{
/* first node in the list, rename database and update formation */
SetFormationDBName(formationId, expectedDBName);
strlcpy(formation->dbname, expectedDBName, NAMEDATALEN);
}
else
{
ereport(ERROR,
(errmsg("node %s:%d with dbname \"%s\" can not be "
"registered in formation \"%s\" "
"which expects dbname \"%s\"",
nodeHost, nodePort, expectedDBName,
formationId,
formation->dbname)));
}
}
/*
* The register_node() function is STRICT but users may have skipped the
* --name option on the create command line. We still want to avoid having
* to scan all the 10 parameters for ISNULL tests, so instead our client
* sends an empty string for the nodename.
*/
JoinAutoFailoverFormation(formation,
strcmp(nodeName, "") == 0 ? NULL : nodeName,
nodeHost,
nodePort,
sysIdentifier,
nodeCluster,
¤tNodeState);
AutoFailoverNode *pgAutoFailoverNode = GetAutoFailoverNode(nodeHost, nodePort);
if (pgAutoFailoverNode == NULL)
{
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("node %s:%d with dbname \"%s\" could not be registered in "
"formation \"%s\", could not get information for node that was inserted",
nodeHost, nodePort, expectedDBName,
formationId)));
}
else
{
char message[BUFSIZE] = { 0 };
LogAndNotifyMessage(
message, BUFSIZE,
"Registering " NODE_FORMAT
" to formation \"%s\" "
"with replication quorum %s and candidate priority %d [%d]",
NODE_FORMAT_ARGS(pgAutoFailoverNode),
pgAutoFailoverNode->formationId,
pgAutoFailoverNode->replicationQuorum ? "true" : "false",
pgAutoFailoverNode->candidatePriority,
currentNodeState.candidatePriority);
}
/*
* When adding a second sync node to a formation that has
* number_sync_standbys set to zero (the default value for single node and
* single standby formations), we switch the default value to 1
* automatically.
*/
if (pgAutoFailoverNode->goalState == REPLICATION_STATE_WAIT_STANDBY &&
formation->number_sync_standbys == 0)
{
AutoFailoverNode *primaryNode =
GetPrimaryNodeInGroup(formationId, currentNodeState.groupId);
List *standbyNodesList = AutoFailoverOtherNodesList(primaryNode);
int syncStandbyNodeCount = CountSyncStandbys(standbyNodesList);
/*
* number_sync_standbys = 0 is a special case in our FSM, because we
* have special handling of a missing standby then, switching to
* wait_primary to disable synchronous replication when the standby is
* not available.
*
* For other values (N) of number_sync_standbys, we require N+1 known
* sync standby nodes, so that you can lose a standby at any point in
* time and still accept writes.
*
* The default value for number_sync_standbys with two standby nodes is
* 1. Because it was set to zero when adding the first standby, we need
* to increment the value when adding a second standby node that
* participates in the replication quorum (a "sync standby" node).
*/
if (syncStandbyNodeCount == 2)
{
char message[BUFSIZE] = { 0 };
formation->number_sync_standbys = 1;
if (!SetFormationNumberSyncStandbys(formationId, 1))
{
ereport(ERROR,
(errmsg("couldn't set the formation \"%s\" "
"number_sync_standbys to 1 now that a third "
"node has been added",
formationId)));
}
LogAndNotifyMessage(
message, BUFSIZE,
"Setting number_sync_standbys to %d for formation %s "
"now that we have %d/%d standby nodes set with replication-quorum.",
formation->number_sync_standbys,
formation->formationId,
syncStandbyNodeCount, list_length(standbyNodesList));
}
}
AutoFailoverNodeState *assignedNodeState =
(AutoFailoverNodeState *) palloc0(sizeof(AutoFailoverNodeState));
assignedNodeState->nodeId = pgAutoFailoverNode->nodeId;
assignedNodeState->groupId = pgAutoFailoverNode->groupId;
assignedNodeState->replicationState = pgAutoFailoverNode->goalState;
assignedNodeState->candidatePriority = pgAutoFailoverNode->candidatePriority;
assignedNodeState->replicationQuorum = pgAutoFailoverNode->replicationQuorum;
/*
* Check that the state selected by the monitor matches the state required
* by the keeper, if any. REPLICATION_STATE_INITIAL means the monitor can
* pick whatever is needed now, depending on the groupId.
*
* The keeper might be confronted to an already existing Postgres instance
* that is running as a primary (not in recovery), and so asking to
* register as a SINGLE. Better error out than ask the keeper to remove
* some unknown data.
*/
if (currentNodeState.replicationState != REPLICATION_STATE_INITIAL)
{
if (currentNodeState.replicationState != pgAutoFailoverNode->goalState)
{
const char *currentState =
ReplicationStateGetName(currentNodeState.replicationState);
const char *goalState =
ReplicationStateGetName(pgAutoFailoverNode->goalState);
ereport(ERROR,
(errmsg("node %s:%d can not be registered in state %s, "
"it should be in state %s",
nodeHost, nodePort, currentState, goalState)));
}
}
ProceedGroupState(pgAutoFailoverNode);
TupleDesc resultDescriptor = NULL;
Datum values[6];
bool isNulls[6];
memset(values, 0, sizeof(values));
memset(isNulls, false, sizeof(isNulls));
values[0] = Int64GetDatum(assignedNodeState->nodeId);
values[1] = Int32GetDatum(assignedNodeState->groupId);
values[2] = ObjectIdGetDatum(
ReplicationStateGetEnum(pgAutoFailoverNode->goalState));
values[3] = Int32GetDatum(assignedNodeState->candidatePriority);
values[4] = BoolGetDatum(assignedNodeState->replicationQuorum);
values[5] = CStringGetTextDatum(pgAutoFailoverNode->nodeName);
TypeFuncClass resultTypeClass =
get_call_result_type(fcinfo, NULL, &resultDescriptor);
if (resultTypeClass != TYPEFUNC_COMPOSITE)
{
ereport(ERROR, (errmsg("return type must be a row type")));
}
HeapTuple resultTuple = heap_form_tuple(resultDescriptor, values, isNulls);
Datum resultDatum = HeapTupleGetDatum(resultTuple);
PG_RETURN_DATUM(resultDatum);
}
/*
* node_active is the main entry-point for the HA state machine. Nodes
* periodically call this function from the moment they start to communicate
* their state to the monitor to obtain their assigned state.
*/
Datum
node_active(PG_FUNCTION_ARGS)
{
checkPgAutoFailoverVersion();
text *formationIdText = PG_GETARG_TEXT_P(0);
char *formationId = text_to_cstring(formationIdText);
int64 currentNodeId = PG_GETARG_INT64(1);
int32 currentGroupId = PG_GETARG_INT32(2);
Oid currentReplicationStateOid = PG_GETARG_OID(3);
bool currentPgIsRunning = PG_GETARG_BOOL(4);
int32 currentTLI = PG_GETARG_INT32(5);
XLogRecPtr currentLSN = PG_GETARG_LSN(6);
text *currentPgsrSyncStateText = PG_GETARG_TEXT_P(7);
char *currentPgsrSyncState = text_to_cstring(currentPgsrSyncStateText);
AutoFailoverNodeState currentNodeState = { 0 };
currentNodeState.nodeId = currentNodeId;
currentNodeState.groupId = currentGroupId;
currentNodeState.replicationState =
EnumGetReplicationState(currentReplicationStateOid);
currentNodeState.reportedTLI = currentTLI;
currentNodeState.reportedLSN = currentLSN;
currentNodeState.pgsrSyncState = SyncStateFromString(currentPgsrSyncState);
currentNodeState.pgIsRunning = currentPgIsRunning;
AutoFailoverNodeState *assignedNodeState =
NodeActive(formationId, ¤tNodeState);
Oid newReplicationStateOid =
ReplicationStateGetEnum(assignedNodeState->replicationState);
TupleDesc resultDescriptor = NULL;
Datum values[5];
bool isNulls[5];
memset(values, 0, sizeof(values));
memset(isNulls, false, sizeof(isNulls));
values[0] = Int64GetDatum(assignedNodeState->nodeId);
values[1] = Int32GetDatum(assignedNodeState->groupId);
values[2] = ObjectIdGetDatum(newReplicationStateOid);
values[3] = Int32GetDatum(assignedNodeState->candidatePriority);
values[4] = BoolGetDatum(assignedNodeState->replicationQuorum);
TypeFuncClass resultTypeClass =
get_call_result_type(fcinfo, NULL, &resultDescriptor);
if (resultTypeClass != TYPEFUNC_COMPOSITE)
{
ereport(ERROR, (errmsg("return type must be a row type")));
}
HeapTuple resultTuple = heap_form_tuple(resultDescriptor, values, isNulls);
Datum resultDatum = HeapTupleGetDatum(resultTuple);
PG_RETURN_DATUM(resultDatum);
}
/*
* NodeActive reports the current state of a node and returns the assigned state.
*/
static AutoFailoverNodeState *
NodeActive(char *formationId, AutoFailoverNodeState *currentNodeState)
{
AutoFailoverNode *pgAutoFailoverNode = GetAutoFailoverNodeById(
currentNodeState->nodeId);
if (pgAutoFailoverNode == NULL)
{
ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("couldn't find node with nodeid %lld",
(long long) currentNodeState->nodeId)));
}
else if (strcmp(pgAutoFailoverNode->formationId, formationId) != 0)
{
ereport(ERROR, (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("node %lld does not belong to formation %s",
(long long) currentNodeState->nodeId,
formationId)));
}
else
{
LockFormation(formationId, ShareLock);
if (pgAutoFailoverNode->reportedState != currentNodeState->replicationState)
{
/*
* The keeper is reporting that it achieved the assigned goal
* state, supposedly. Log the new reported state as an event, and
* notify it.
*/
char message[BUFSIZE] = { 0 };
if (pgAutoFailoverNode->goalState == REPLICATION_STATE_REPORT_LSN)
{
LogAndNotifyMessage(
message, BUFSIZE,
"New state is reported by " NODE_FORMAT
" with LSN %X/%X: %s",
NODE_FORMAT_ARGS(pgAutoFailoverNode),
(uint32) (pgAutoFailoverNode->reportedLSN >> 32),
(uint32) pgAutoFailoverNode->reportedLSN,
ReplicationStateGetName(currentNodeState->replicationState));
}
else
{
LogAndNotifyMessage(
message, BUFSIZE,
"New state is reported by " NODE_FORMAT
": \"%s\"",
NODE_FORMAT_ARGS(pgAutoFailoverNode),
ReplicationStateGetName(currentNodeState->replicationState));
}
pgAutoFailoverNode->reportedState = currentNodeState->replicationState;
pgAutoFailoverNode->pgsrSyncState = currentNodeState->pgsrSyncState;
pgAutoFailoverNode->reportedLSN = currentNodeState->reportedLSN;
NotifyStateChange(pgAutoFailoverNode, message);
}
/*
* Report the current state. The state might not have changed, but in
* that case we still update the last report time.
*/
ReportAutoFailoverNodeState(pgAutoFailoverNode->nodeHost,
pgAutoFailoverNode->nodePort,
currentNodeState->replicationState,
currentNodeState->pgIsRunning,
currentNodeState->pgsrSyncState,
currentNodeState->reportedTLI,
currentNodeState->reportedLSN);
}
LockNodeGroup(formationId, currentNodeState->groupId, ExclusiveLock);
ProceedGroupState(pgAutoFailoverNode);
AutoFailoverNodeState *assignedNodeState =
(AutoFailoverNodeState *) palloc0(sizeof(AutoFailoverNodeState));
assignedNodeState->nodeId = pgAutoFailoverNode->nodeId;
assignedNodeState->groupId = pgAutoFailoverNode->groupId;
assignedNodeState->replicationState = pgAutoFailoverNode->goalState;
assignedNodeState->candidatePriority = pgAutoFailoverNode->candidatePriority;
assignedNodeState->replicationQuorum = pgAutoFailoverNode->replicationQuorum;
return assignedNodeState;
}
/*
* JoinAutoFailoverFormation adds a new node to a AutoFailover formation.
*/
static void
JoinAutoFailoverFormation(AutoFailoverFormation *formation,
char *nodeName, char *nodeHost, int nodePort,
uint64 sysIdentifier, char *nodeCluster,
AutoFailoverNodeState *currentNodeState)
{
int groupId = -1;
ReplicationState initialState = REPLICATION_STATE_UNKNOWN;
/* in a Postgres formation, we have a single groupId, and it's groupId 0 */
if (formation->kind == FORMATION_KIND_PGSQL)
{
/*
* Register with groupId -1 to get one assigned by the monitor, or with
* the groupId you know you want to join. In a Postgres (pgsql)
* formation it's all down to groupId 0 anyway.
*/
if (currentNodeState->groupId > 0)
{
ereport(ERROR,
(errmsg("node %s:%d can not be registered in group %d "
"in formation \"%s\" of type pgsql",
nodeHost, nodePort,
currentNodeState->groupId, formation->formationId),
errdetail("in a pgsql formation, there can be only one "
"group, with groupId 0")));
}
groupId = currentNodeState->groupId = 0;
}
/* either a Citus groupId was asked for, or we're in group 0 for pgsql */
if (currentNodeState->groupId >= 0)
{
groupId = currentNodeState->groupId;
/*
* Now that we have a groupId, take an exclusive lock to avoid race
* conditions during registration, as the initial target state depends
* on the other nodes in the same group.
*/
LockNodeGroup(formation->formationId, groupId, ExclusiveLock);
List *groupNodeList =
AutoFailoverNodeGroup(formation->formationId, groupId);
/*
* Target group is empty: to make it simple to reason about the roles
* in a group, we only ever accept a primary node first. Then, any
* other node in the same group should be a standby. That's easy.
*/
if (list_length(groupNodeList) == 0 &&
currentNodeState->candidatePriority > 0)
{
initialState = REPLICATION_STATE_SINGLE;
}
/* target group already has a primary, any other node is a standby */
else if (formation->opt_secondary)
{
initialState = REPLICATION_STATE_WAIT_STANDBY;
/* if we have a primary node, pg_basebackup from it */
AutoFailoverNode *primaryNode =
GetPrimaryNodeInGroup(
formation->formationId,
currentNodeState->groupId);
/* we might be in the middle of a failover */
List *nodesGroupList =
AutoFailoverNodeGroup(
formation->formationId,
currentNodeState->groupId);
/* if we don't have a primary, look for a node being promoted */
AutoFailoverNode *nodeBeingPromoted = NULL;
/* we might have an upstream node that's not a failover candidate */
bool foundUpstreamNode = false;
if (primaryNode == NULL)
{
nodeBeingPromoted =
FindCandidateNodeBeingPromoted(
nodesGroupList);
}
/*
* If we don't have a primary node and we also don't have a node
* being promoted, it might be that all we have is a list of
* nodes with candidatePriority zero.
*
* When that happens, those nodes are assigned REPORT_LSN, in case
* a candidate could be promoted (and maybe fast-forwarded).
*
* If we find even a single node in REPORT_LSN and with candidate
* priority zero, we have an upstream node for creating a new
* node, that can then be promoted as the new primary.
*/
if (primaryNode == NULL && nodeBeingPromoted == NULL)
{
ListCell *nodeCell = NULL;
foreach(nodeCell, nodesGroupList)
{
AutoFailoverNode *node =
(AutoFailoverNode *) lfirst(nodeCell);
if (node->candidatePriority == 0 &&
IsCurrentState(node, REPLICATION_STATE_REPORT_LSN))
{
foundUpstreamNode = true;
break;
}
}
if (foundUpstreamNode)
{
initialState = REPLICATION_STATE_REPORT_LSN;
}
}
/*
* If we can't figure it out, have the client handle the situation.
*/
if (!(primaryNode || nodeBeingPromoted || foundUpstreamNode))
{
ereport(ERROR,
(errcode(ERRCODE_OBJECT_IN_USE),
errmsg("JoinAutoFailoverFormation couldn't find the "
" primary node in formation \"%s\", group %d",
formation->formationId,
currentNodeState->groupId),
errhint("Retry registering in a moment")));
}
}
/* formation->opt_secondary is false */
else
{
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("Formation \"%s\" does not allow secondary nodes",
formation->formationId),
errhint("use pg_autoctl enable secondary")));
}
}
else
{
/*
* In a Citus formation, the register policy is to build a set of
* workers with each a primary and a secondary, including the
* coordinator.
*
* That's the policy implemented in AssignGroupId.
*/
groupId = AssignGroupId(formation, nodeHost, nodePort, &initialState);
}
AddAutoFailoverNode(formation->formationId,
formation->kind,
currentNodeState->nodeId,
groupId,
nodeName,
nodeHost,
nodePort,
sysIdentifier,
initialState,
currentNodeState->replicationState,
currentNodeState->candidatePriority,
currentNodeState->replicationQuorum,
nodeCluster);
currentNodeState->groupId = groupId;
}
/*
* AssignGroupId assigns a group ID to a new node and returns it.
*/
static int
AssignGroupId(AutoFailoverFormation *formation, char *nodeHost, int nodePort,
ReplicationState *initialState)
{
int groupId = -1;
int candidateGroupId =
/*
* a Citus formation's coordinator always asks for groupId 0, and the
* workers are not allowed to ask for groupId 0. So here, when the
* formation is a citus formation, then candidateGroupId begins at 1.
*/
formation->kind == FORMATION_KIND_CITUS ? 1 : 0;
do {
List *groupNodeList =
AutoFailoverNodeGroup(formation->formationId, candidateGroupId);
if (list_length(groupNodeList) == 0)
{
groupId = candidateGroupId;
*initialState = REPLICATION_STATE_SINGLE;
}
else if (formation->opt_secondary && list_length(groupNodeList) == 1)
{
groupId = candidateGroupId;
*initialState = REPLICATION_STATE_WAIT_STANDBY;
}
else
{
candidateGroupId++;
}
} while (groupId == -1);
return groupId;
}
/*
* get_primary returns the node in a group which currently takes writes.
*/
Datum
get_primary(PG_FUNCTION_ARGS)
{
checkPgAutoFailoverVersion();
text *formationIdText = PG_GETARG_TEXT_P(0);
char *formationId = text_to_cstring(formationIdText);
int32 groupId = PG_GETARG_INT32(1);
TupleDesc resultDescriptor = NULL;
Datum values[4];
bool isNulls[4];
AutoFailoverNode *primaryNode =
GetPrimaryOrDemotedNodeInGroup(formationId, groupId);
if (primaryNode == NULL)
{
ereport(ERROR, (errmsg("group has no writable node right now")));
}
memset(values, 0, sizeof(values));
memset(isNulls, false, sizeof(isNulls));
values[0] = Int64GetDatum(primaryNode->nodeId);
values[1] = CStringGetTextDatum(primaryNode->nodeName);
values[2] = CStringGetTextDatum(primaryNode->nodeHost);
values[3] = Int32GetDatum(primaryNode->nodePort);
TypeFuncClass resultTypeClass = get_call_result_type(fcinfo, NULL, &resultDescriptor);
if (resultTypeClass != TYPEFUNC_COMPOSITE)
{
ereport(ERROR, (errmsg("return type must be a row type")));
}
HeapTuple resultTuple = heap_form_tuple(resultDescriptor, values, isNulls);
Datum resultDatum = HeapTupleGetDatum(resultTuple);
PG_RETURN_DATUM(resultDatum);
}
typedef struct get_nodes_fctx
{
List *nodesList;
} get_nodes_fctx;
/*
* get_nodes returns all the node in a group, if any.
*/
Datum
get_nodes(PG_FUNCTION_ARGS)
{
checkPgAutoFailoverVersion();
FuncCallContext *funcctx;
get_nodes_fctx *fctx;
MemoryContext oldcontext;
/* stuff done only on the first call of the function */
if (SRF_IS_FIRSTCALL())
{
text *formationIdText = PG_GETARG_TEXT_P(0);
char *formationId = text_to_cstring(formationIdText);
if (PG_ARGISNULL(0))
{
ereport(ERROR, (errmsg("formation_id must not be null")));
}
checkPgAutoFailoverVersion();
/* create a function context for cross-call persistence */
funcctx = SRF_FIRSTCALL_INIT();
/*
* switch to memory context appropriate for multiple function calls
*/
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* allocate memory for user context */
fctx = (get_nodes_fctx *) palloc(sizeof(get_nodes_fctx));
/*
* Use fctx to keep state from call to call. Seed current with the
* original start value
*/
if (PG_ARGISNULL(1))
{
fctx->nodesList = AllAutoFailoverNodes(formationId);
}
else
{
int32 groupId = PG_GETARG_INT32(1);
fctx->nodesList = AutoFailoverAllNodesInGroup(formationId, groupId);
}
funcctx->user_fctx = fctx;
MemoryContextSwitchTo(oldcontext);
}
/* stuff done on every call of the function */
funcctx = SRF_PERCALL_SETUP();
/*
* get the saved state and use current as the result for this iteration
*/
fctx = funcctx->user_fctx;
if (fctx->nodesList != NIL)
{
TupleDesc resultDescriptor = NULL;
Datum values[6];
bool isNulls[6];
AutoFailoverNode *node = (AutoFailoverNode *) linitial(fctx->nodesList);
memset(values, 0, sizeof(values));
memset(isNulls, false, sizeof(isNulls));
values[0] = Int64GetDatum(node->nodeId);
values[1] = CStringGetTextDatum(node->nodeName);
values[2] = CStringGetTextDatum(node->nodeHost);
values[3] = Int32GetDatum(node->nodePort);
values[4] = LSNGetDatum(node->reportedLSN);
values[5] = BoolGetDatum(CanTakeWritesInState(node->reportedState));
TypeFuncClass resultTypeClass = get_call_result_type(fcinfo, NULL,
&resultDescriptor);
if (resultTypeClass != TYPEFUNC_COMPOSITE)
{
ereport(ERROR, (errmsg("return type must be a row type")));
}
HeapTuple resultTuple = heap_form_tuple(resultDescriptor, values, isNulls);
Datum resultDatum = HeapTupleGetDatum(resultTuple);
/* prepare next SRF call */
fctx->nodesList = list_delete_first(fctx->nodesList);
SRF_RETURN_NEXT(funcctx, resultDatum);
}
SRF_RETURN_DONE(funcctx);
}
/*
* get_other_node is not supported anymore, but we might want to be able to
* have the pgautofailover.so for 1.1 co-exists with the SQL definitions for
* 1.0 at least during an upgrade, or to test upgrades.
*/
Datum
get_other_node(PG_FUNCTION_ARGS)
{
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("pgautofailover.get_other_node is no longer supported")));
}
/*
* get_other_nodes returns the other node in a group, if any.
*/
Datum
get_other_nodes(PG_FUNCTION_ARGS)
{
checkPgAutoFailoverVersion();
FuncCallContext *funcctx;
get_nodes_fctx *fctx;
MemoryContext oldcontext;
/* stuff done only on the first call of the function */
if (SRF_IS_FIRSTCALL())
{
int64 nodeId = PG_GETARG_INT64(0);
checkPgAutoFailoverVersion();
/* create a function context for cross-call persistence */
funcctx = SRF_FIRSTCALL_INIT();
/*
* switch to memory context appropriate for multiple function calls
*/
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* allocate memory for user context */
fctx = (get_nodes_fctx *) palloc(sizeof(get_nodes_fctx));
/*
* Use fctx to keep state from call to call. Seed current with the
* original start value
*/
AutoFailoverNode *activeNode = GetAutoFailoverNodeById(nodeId);
if (activeNode == NULL)
{
ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("node %lld is not registered",
(long long) nodeId)));
}
if (PG_NARGS() == 1)
{
fctx->nodesList = AutoFailoverOtherNodesList(activeNode);
}
else if (PG_NARGS() == 2)
{
Oid currentReplicationStateOid = PG_GETARG_OID(1);
ReplicationState currentState =
EnumGetReplicationState(currentReplicationStateOid);
fctx->nodesList =
AutoFailoverOtherNodesListInState(activeNode, currentState);
}
else
{
/* that's a bug in the SQL exposure of that function */
ereport(ERROR,
(errmsg("unsupported number of arguments (%d)",
PG_NARGS())));
}
funcctx->user_fctx = fctx;
MemoryContextSwitchTo(oldcontext);
}
/* stuff done on every call of the function */
funcctx = SRF_PERCALL_SETUP();
/*
* get the saved state and use current as the result for this iteration
*/
fctx = funcctx->user_fctx;
if (fctx->nodesList != NIL)
{
TupleDesc resultDescriptor = NULL;
Datum values[6];
bool isNulls[6];
AutoFailoverNode *node = (AutoFailoverNode *) linitial(fctx->nodesList);
memset(values, 0, sizeof(values));
memset(isNulls, false, sizeof(isNulls));
values[0] = Int64GetDatum(node->nodeId);
values[1] = CStringGetTextDatum(node->nodeName);
values[2] = CStringGetTextDatum(node->nodeHost);
values[3] = Int32GetDatum(node->nodePort);
values[4] = LSNGetDatum(node->reportedLSN);
values[5] = BoolGetDatum(CanTakeWritesInState(node->reportedState));
TypeFuncClass resultTypeClass = get_call_result_type(fcinfo, NULL,
&resultDescriptor);
if (resultTypeClass != TYPEFUNC_COMPOSITE)
{
ereport(ERROR, (errmsg("return type must be a row type")));
}
HeapTuple resultTuple = heap_form_tuple(resultDescriptor, values, isNulls);
Datum resultDatum = HeapTupleGetDatum(resultTuple);
/* prepare next SRF call */
fctx->nodesList = list_delete_first(fctx->nodesList);
SRF_RETURN_NEXT(funcctx, resultDatum);
}