-
Notifications
You must be signed in to change notification settings - Fork 643
/
node_metadata.c
3206 lines (2672 loc) · 94.7 KB
/
node_metadata.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
/*
* node_metadata.c
* Functions that operate on pg_dist_node
*
* Copyright (c) Citus Data, Inc.
*/
#include "postgres.h"
#include "miscadmin.h"
#include "funcapi.h"
#include "utils/plancache.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/htup.h"
#include "access/htup_details.h"
#include "access/skey.h"
#include "access/skey.h"
#include "access/tupmacs.h"
#include "access/xact.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "commands/sequence.h"
#include "distributed/citus_acquire_lock.h"
#include "distributed/citus_safe_lib.h"
#include "distributed/colocation_utils.h"
#include "distributed/commands.h"
#include "distributed/commands/utility_hook.h"
#include "distributed/connection_management.h"
#include "distributed/maintenanced.h"
#include "distributed/coordinator_protocol.h"
#include "distributed/metadata_utility.h"
#include "distributed/metadata/distobject.h"
#include "distributed/metadata_cache.h"
#include "distributed/metadata_sync.h"
#include "distributed/multi_join_order.h"
#include "distributed/multi_router_planner.h"
#include "distributed/pg_dist_node.h"
#include "distributed/pg_dist_node_metadata.h"
#include "distributed/reference_table_utils.h"
#include "distributed/remote_commands.h"
#include "distributed/resource_lock.h"
#include "distributed/shardinterval_utils.h"
#include "distributed/multi_partitioning_utils.h"
#include "distributed/shared_connection_stats.h"
#include "distributed/string_utils.h"
#include "distributed/metadata/pg_dist_object.h"
#include "distributed/transaction_recovery.h"
#include "distributed/version_compat.h"
#include "distributed/worker_manager.h"
#include "distributed/worker_transaction.h"
#include "executor/spi.h"
#include "lib/stringinfo.h"
#include "postmaster/postmaster.h"
#include "storage/bufmgr.h"
#include "storage/lmgr.h"
#include "storage/lock.h"
#include "storage/fd.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/relcache.h"
#define INVALID_GROUP_ID -1
/* default group size */
int GroupSize = 1;
/* config variable managed via guc.c */
char *CurrentCluster = "default";
/* did current transaction modify pg_dist_node? */
bool TransactionModifiedNodeMetadata = false;
bool EnableMetadataSync = true;
typedef struct NodeMetadata
{
int32 groupId;
char *nodeRack;
bool hasMetadata;
bool metadataSynced;
bool isActive;
Oid nodeRole;
bool shouldHaveShards;
char *nodeCluster;
} NodeMetadata;
/* local function forward declarations */
static void RemoveNodeFromCluster(char *nodeName, int32 nodePort);
static void ErrorIfNodeContainsNonRemovablePlacements(WorkerNode *workerNode);
static bool PlacementHasActivePlacementOnAnotherGroup(GroupShardPlacement
*sourcePlacement);
static int AddNodeMetadata(char *nodeName, int32 nodePort, NodeMetadata *nodeMetadata,
bool *nodeAlreadyExists, bool localOnly);
static int AddNodeMetadataViaMetadataContext(char *nodeName, int32 nodePort,
NodeMetadata *nodeMetadata,
bool *nodeAlreadyExists);
static HeapTuple GetNodeTuple(const char *nodeName, int32 nodePort);
static HeapTuple GetNodeByNodeId(int32 nodeId);
static int32 GetNextGroupId(void);
static int GetNextNodeId(void);
static void InsertPlaceholderCoordinatorRecord(void);
static void InsertNodeRow(int nodeid, char *nodename, int32 nodeport,
NodeMetadata *nodeMetadata);
static void DeleteNodeRow(char *nodename, int32 nodeport);
static void BlockDistributedQueriesOnMetadataNodes(void);
static WorkerNode * TupleToWorkerNode(TupleDesc tupleDescriptor, HeapTuple heapTuple);
static bool NodeIsLocal(WorkerNode *worker);
static void SetLockTimeoutLocally(int32 lock_cooldown);
static void UpdateNodeLocation(int32 nodeId, char *newNodeName, int32 newNodePort,
bool localOnly);
static bool UnsetMetadataSyncedForAllWorkers(void);
static char * GetMetadataSyncCommandToSetNodeColumn(WorkerNode *workerNode,
int columnIndex,
Datum value);
static char * NodeHasmetadataUpdateCommand(uint32 nodeId, bool hasMetadata);
static char * NodeMetadataSyncedUpdateCommand(uint32 nodeId, bool metadataSynced);
static void ErrorIfCoordinatorMetadataSetFalse(WorkerNode *workerNode, Datum value,
char *field);
static WorkerNode * SetShouldHaveShards(WorkerNode *workerNode, bool shouldHaveShards);
static WorkerNode * FindNodeAnyClusterByNodeId(uint32 nodeId);
static void ErrorIfAnyNodeNotExist(List *nodeList);
static void UpdateLocalGroupIdsViaMetadataContext(MetadataSyncContext *context);
static void SendDeletionCommandsForReplicatedTablePlacements(
MetadataSyncContext *context);
static void SyncNodeMetadata(MetadataSyncContext *context);
static void SetNodeStateViaMetadataContext(MetadataSyncContext *context,
WorkerNode *workerNode,
Datum value);
static void MarkNodesNotSyncedInLoopBackConnection(MetadataSyncContext *context,
pid_t parentSessionPid);
static void EnsureParentSessionHasExclusiveLockOnPgDistNode(pid_t parentSessionPid);
static void SetNodeMetadata(MetadataSyncContext *context, bool localOnly);
static void EnsureTransactionalMetadataSyncMode(void);
static void LockShardsInWorkerPlacementList(WorkerNode *workerNode, LOCKMODE
lockMode);
static BackgroundWorkerHandle * CheckBackgroundWorkerToObtainLocks(int32 lock_cooldown);
static BackgroundWorkerHandle * LockPlacementsWithBackgroundWorkersInPrimaryNode(
WorkerNode *workerNode, bool force, int32 lock_cooldown);
/* Function definitions go here */
/* declarations for dynamic loading */
PG_FUNCTION_INFO_V1(citus_set_coordinator_host);
PG_FUNCTION_INFO_V1(citus_add_node);
PG_FUNCTION_INFO_V1(master_add_node);
PG_FUNCTION_INFO_V1(citus_add_inactive_node);
PG_FUNCTION_INFO_V1(master_add_inactive_node);
PG_FUNCTION_INFO_V1(citus_add_secondary_node);
PG_FUNCTION_INFO_V1(master_add_secondary_node);
PG_FUNCTION_INFO_V1(citus_set_node_property);
PG_FUNCTION_INFO_V1(master_set_node_property);
PG_FUNCTION_INFO_V1(citus_remove_node);
PG_FUNCTION_INFO_V1(master_remove_node);
PG_FUNCTION_INFO_V1(citus_disable_node);
PG_FUNCTION_INFO_V1(master_disable_node);
PG_FUNCTION_INFO_V1(citus_activate_node);
PG_FUNCTION_INFO_V1(master_activate_node);
PG_FUNCTION_INFO_V1(citus_update_node);
PG_FUNCTION_INFO_V1(citus_pause_node_within_txn);
PG_FUNCTION_INFO_V1(master_update_node);
PG_FUNCTION_INFO_V1(get_shard_id_for_distribution_column);
PG_FUNCTION_INFO_V1(citus_nodename_for_nodeid);
PG_FUNCTION_INFO_V1(citus_nodeport_for_nodeid);
PG_FUNCTION_INFO_V1(citus_coordinator_nodeid);
PG_FUNCTION_INFO_V1(citus_is_coordinator);
PG_FUNCTION_INFO_V1(citus_internal_mark_node_not_synced);
/*
* DefaultNodeMetadata creates a NodeMetadata struct with the fields set to
* sane defaults, e.g. nodeRack = WORKER_DEFAULT_RACK.
*/
static NodeMetadata
DefaultNodeMetadata()
{
NodeMetadata nodeMetadata;
/* ensure uninitialized padding doesn't escape the function */
memset_struct_0(nodeMetadata);
nodeMetadata.nodeRack = WORKER_DEFAULT_RACK;
nodeMetadata.shouldHaveShards = true;
nodeMetadata.groupId = INVALID_GROUP_ID;
return nodeMetadata;
}
/*
* citus_set_coordinator_host configures the hostname and port through which worker
* nodes can connect to the coordinator.
*/
Datum
citus_set_coordinator_host(PG_FUNCTION_ARGS)
{
CheckCitusVersion(ERROR);
text *nodeName = PG_GETARG_TEXT_P(0);
int32 nodePort = PG_GETARG_INT32(1);
char *nodeNameString = text_to_cstring(nodeName);
NodeMetadata nodeMetadata = DefaultNodeMetadata();
nodeMetadata.groupId = 0;
nodeMetadata.shouldHaveShards = false;
nodeMetadata.nodeRole = PG_GETARG_OID(2);
Name nodeClusterName = PG_GETARG_NAME(3);
nodeMetadata.nodeCluster = NameStr(*nodeClusterName);
/*
* We do not allow metadata operations on secondary nodes in nontransactional
* sync mode.
*/
if (nodeMetadata.nodeRole == SecondaryNodeRoleId())
{
EnsureTransactionalMetadataSyncMode();
}
bool isCoordinatorInMetadata = false;
WorkerNode *coordinatorNode = PrimaryNodeForGroup(COORDINATOR_GROUP_ID,
&isCoordinatorInMetadata);
if (!isCoordinatorInMetadata)
{
bool nodeAlreadyExists = false;
bool localOnly = false;
/* add the coordinator to pg_dist_node if it was not already added */
AddNodeMetadata(nodeNameString, nodePort, &nodeMetadata,
&nodeAlreadyExists, localOnly);
/* we just checked */
Assert(!nodeAlreadyExists);
}
else
{
/*
* since AddNodeMetadata takes an exclusive lock on pg_dist_node, we
* do not need to worry about concurrent changes (e.g. deletion) and
* can proceed to update immediately.
*/
bool localOnly = false;
UpdateNodeLocation(coordinatorNode->nodeId, nodeNameString, nodePort, localOnly);
/* clear cached plans that have the old host/port */
ResetPlanCache();
}
TransactionModifiedNodeMetadata = true;
PG_RETURN_VOID();
}
/*
* EnsureTransactionalMetadataSyncMode ensures metadata sync mode is transactional.
*/
static void
EnsureTransactionalMetadataSyncMode(void)
{
if (MetadataSyncTransMode == METADATA_SYNC_NON_TRANSACTIONAL)
{
ereport(ERROR, (errmsg("this operation cannot be completed in nontransactional "
"metadata sync mode"),
errhint("SET citus.metadata_sync_mode to 'transactional'")));
}
}
/*
* citus_add_node function adds a new node to the cluster and returns its id. It also
* replicates all reference tables to the new node.
*/
Datum
citus_add_node(PG_FUNCTION_ARGS)
{
CheckCitusVersion(ERROR);
EnsureSuperUser();
EnsureCoordinator();
text *nodeName = PG_GETARG_TEXT_P(0);
int32 nodePort = PG_GETARG_INT32(1);
char *nodeNameString = text_to_cstring(nodeName);
NodeMetadata nodeMetadata = DefaultNodeMetadata();
bool nodeAlreadyExists = false;
nodeMetadata.groupId = PG_GETARG_INT32(2);
/*
* During tests this function is called before nodeRole and nodeCluster have been
* created.
*/
if (PG_NARGS() == 3)
{
nodeMetadata.nodeRole = InvalidOid;
nodeMetadata.nodeCluster = "default";
}
else
{
Name nodeClusterName = PG_GETARG_NAME(4);
nodeMetadata.nodeCluster = NameStr(*nodeClusterName);
nodeMetadata.nodeRole = PG_GETARG_OID(3);
}
if (nodeMetadata.groupId == COORDINATOR_GROUP_ID)
{
/* by default, we add the coordinator without shards */
nodeMetadata.shouldHaveShards = false;
}
/*
* We do not allow metadata operations on secondary nodes in nontransactional
* sync mode.
*/
if (nodeMetadata.nodeRole == SecondaryNodeRoleId())
{
EnsureTransactionalMetadataSyncMode();
}
if (MetadataSyncTransMode == METADATA_SYNC_NON_TRANSACTIONAL &&
IsMultiStatementTransaction())
{
/*
* prevent inside transaction block as we use bare connections which can
* lead deadlock
*/
ereport(ERROR, (errmsg("do not add node in transaction block "
"when the sync mode is nontransactional"),
errhint("add the node after SET citus.metadata_sync_mode "
"TO 'transactional'")));
}
int nodeId = AddNodeMetadataViaMetadataContext(nodeNameString, nodePort,
&nodeMetadata,
&nodeAlreadyExists);
TransactionModifiedNodeMetadata = true;
PG_RETURN_INT32(nodeId);
}
/*
* master_add_node is a wrapper function for old UDF name.
*/
Datum
master_add_node(PG_FUNCTION_ARGS)
{
return citus_add_node(fcinfo);
}
/*
* citus_add_inactive_node function adds a new node to the cluster as inactive node
* and returns id of the newly added node. It does not replicate reference
* tables to the new node, it only adds new node to the pg_dist_node table.
*/
Datum
citus_add_inactive_node(PG_FUNCTION_ARGS)
{
CheckCitusVersion(ERROR);
text *nodeName = PG_GETARG_TEXT_P(0);
int32 nodePort = PG_GETARG_INT32(1);
char *nodeNameString = text_to_cstring(nodeName);
Name nodeClusterName = PG_GETARG_NAME(4);
NodeMetadata nodeMetadata = DefaultNodeMetadata();
bool nodeAlreadyExists = false;
nodeMetadata.groupId = PG_GETARG_INT32(2);
nodeMetadata.nodeRole = PG_GETARG_OID(3);
nodeMetadata.nodeCluster = NameStr(*nodeClusterName);
if (nodeMetadata.groupId == COORDINATOR_GROUP_ID)
{
ereport(ERROR, (errmsg("coordinator node cannot be added as inactive node")));
}
/*
* We do not allow metadata operations on secondary nodes in nontransactional
* sync mode.
*/
if (nodeMetadata.nodeRole == SecondaryNodeRoleId())
{
EnsureTransactionalMetadataSyncMode();
}
bool localOnly = false;
int nodeId = AddNodeMetadata(nodeNameString, nodePort, &nodeMetadata,
&nodeAlreadyExists, localOnly);
TransactionModifiedNodeMetadata = true;
PG_RETURN_INT32(nodeId);
}
/*
* master_add_inactive_node is a wrapper function for old UDF name.
*/
Datum
master_add_inactive_node(PG_FUNCTION_ARGS)
{
return citus_add_inactive_node(fcinfo);
}
/*
* citus_add_secondary_node adds a new secondary node to the cluster. It accepts as
* arguments the primary node it should share a group with.
*/
Datum
citus_add_secondary_node(PG_FUNCTION_ARGS)
{
CheckCitusVersion(ERROR);
text *nodeName = PG_GETARG_TEXT_P(0);
int32 nodePort = PG_GETARG_INT32(1);
char *nodeNameString = text_to_cstring(nodeName);
text *primaryName = PG_GETARG_TEXT_P(2);
int32 primaryPort = PG_GETARG_INT32(3);
char *primaryNameString = text_to_cstring(primaryName);
Name nodeClusterName = PG_GETARG_NAME(4);
NodeMetadata nodeMetadata = DefaultNodeMetadata();
bool nodeAlreadyExists = false;
nodeMetadata.groupId = GroupForNode(primaryNameString, primaryPort);
nodeMetadata.nodeCluster = NameStr(*nodeClusterName);
nodeMetadata.nodeRole = SecondaryNodeRoleId();
nodeMetadata.isActive = true;
/*
* We do not allow metadata operations on secondary nodes in nontransactional
* sync mode.
*/
EnsureTransactionalMetadataSyncMode();
bool localOnly = false;
int nodeId = AddNodeMetadata(nodeNameString, nodePort, &nodeMetadata,
&nodeAlreadyExists, localOnly);
TransactionModifiedNodeMetadata = true;
PG_RETURN_INT32(nodeId);
}
/*
* master_add_secondary_node is a wrapper function for old UDF name.
*/
Datum
master_add_secondary_node(PG_FUNCTION_ARGS)
{
return citus_add_secondary_node(fcinfo);
}
/*
* citus_remove_node function removes the provided node from the pg_dist_node table of
* the master node and all nodes with metadata.
* The call to the citus_remove_node should be done by the super user and the specified
* node should not have any active placements.
* This function also deletes all reference table placements belong to the given node from
* pg_dist_placement, but it does not drop actual placement at the node. In the case of
* re-adding the node, citus_add_node first drops and re-creates the reference tables.
*/
Datum
citus_remove_node(PG_FUNCTION_ARGS)
{
CheckCitusVersion(ERROR);
text *nodeNameText = PG_GETARG_TEXT_P(0);
int32 nodePort = PG_GETARG_INT32(1);
RemoveNodeFromCluster(text_to_cstring(nodeNameText), nodePort);
TransactionModifiedNodeMetadata = true;
PG_RETURN_VOID();
}
/*
* master_remove_node is a wrapper function for old UDF name.
*/
Datum
master_remove_node(PG_FUNCTION_ARGS)
{
return citus_remove_node(fcinfo);
}
/*
* citus_disable_node function sets isactive value of the provided node as inactive at
* coordinator and all nodes with metadata regardless of the node having an active shard
* placement.
*
* The call to the citus_disable_node must be done by the super user.
*
* This function also deletes all reference table placements belong to the given node
* from pg_dist_placement, but it does not drop actual placement at the node. In the case
* of re-activating the node, citus_add_node first drops and re-creates the reference
* tables.
*/
Datum
citus_disable_node(PG_FUNCTION_ARGS)
{
text *nodeNameText = PG_GETARG_TEXT_P(0);
int32 nodePort = PG_GETARG_INT32(1);
bool synchronousDisableNode = PG_GETARG_BOOL(2);
char *nodeName = text_to_cstring(nodeNameText);
WorkerNode *workerNode = ModifiableWorkerNode(nodeName, nodePort);
/* there is no concept of invalid coordinator */
bool isActive = false;
ErrorIfCoordinatorMetadataSetFalse(workerNode, BoolGetDatum(isActive),
"isactive");
/*
* We do not allow metadata operations on secondary nodes in nontransactional
* sync mode.
*/
if (NodeIsSecondary(workerNode))
{
EnsureTransactionalMetadataSyncMode();
}
WorkerNode *firstWorkerNode = GetFirstPrimaryWorkerNode();
bool disablingFirstNode =
(firstWorkerNode && firstWorkerNode->nodeId == workerNode->nodeId);
if (disablingFirstNode && !synchronousDisableNode)
{
/*
* We sync metadata async and optionally in the background worker,
* it would mean that some nodes might get the updates while other
* not. And, if the node metadata that is changing is the first
* worker node, the problem gets nasty. We serialize modifications
* to replicated tables by acquiring locks on the first worker node.
*
* If some nodes get the metadata changes and some do not, they'd be
* acquiring the locks on different nodes. Hence, having the
* possibility of diverged shard placements for the same shard.
*
* To prevent that, we currently do not allow disabling the first
* worker node unless it is explicitly opted synchronous.
*/
ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("disabling the first worker node in the "
"metadata is not allowed"),
errhint("You can force disabling node, SELECT "
"citus_disable_node('%s', %d, "
"synchronous:=true);",
workerNode->workerName,
nodePort),
errdetail("Citus uses the first worker node in the "
"metadata for certain internal operations when "
"replicated tables are modified. Synchronous mode "
"ensures that all nodes have the same view of the "
"first worker node, which is used for certain "
"locking operations.")));
}
/*
* First, locally mark the node as inactive. We'll later trigger background
* worker to sync the metadata changes to the relevant nodes.
*/
workerNode =
SetWorkerColumnLocalOnly(workerNode,
Anum_pg_dist_node_isactive,
BoolGetDatum(isActive));
if (NodeIsPrimary(workerNode))
{
/*
* We do not allow disabling nodes if it contains any
* primary placement that is the "only" active placement
* for any given shard.
*/
ErrorIfNodeContainsNonRemovablePlacements(workerNode);
}
TransactionModifiedNodeMetadata = true;
if (synchronousDisableNode)
{
/*
* The user might pick between sync vs async options.
* - Pros for the sync option:
* (a) the changes become visible on the cluster immediately
* (b) even if the first worker node is disabled, there is no
* risk of divergence of the placements of replicated shards
* - Cons for the sync options:
* (a) Does not work within 2PC transaction (e.g., BEGIN;
* citus_disable_node(); PREPARE TRANSACTION ...);
* (b) If there are multiple node failures (e.g., one another node
* than the current node being disabled), the sync option would
* fail because it'd try to sync the metadata changes to a node
* that is not up and running.
*/
if (firstWorkerNode && firstWorkerNode->nodeId == workerNode->nodeId)
{
/*
* We cannot let any modification query on a replicated table to run
* concurrently with citus_disable_node() on the first worker node. If
* we let that, some worker nodes might calculate FirstWorkerNode()
* different than others. See LockShardListResourcesOnFirstWorker()
* for the details.
*/
BlockDistributedQueriesOnMetadataNodes();
}
SyncNodeMetadataToNodes();
}
else if (UnsetMetadataSyncedForAllWorkers())
{
/*
* We have not propagated the node metadata changes yet, make sure that all the
* active nodes get the metadata updates. We defer this operation to the
* background worker to make it possible disabling nodes when multiple nodes
* are down.
*
* Note that the active placements reside on the active nodes. Hence, when
* Citus finds active placements, it filters out the placements that are on
* the disabled nodes. That's why, we don't have to change/sync placement
* metadata at this point. Instead, we defer that to citus_activate_node()
* where we expect all nodes up and running.
*/
TriggerNodeMetadataSyncOnCommit();
}
PG_RETURN_VOID();
}
/*
* BlockDistributedQueriesOnMetadataNodes blocks all the modification queries on
* all nodes. Hence, should be used with caution.
*/
static void
BlockDistributedQueriesOnMetadataNodes(void)
{
/* first, block on the coordinator */
LockRelationOid(DistNodeRelationId(), ExclusiveLock);
/*
* Note that we might re-design this lock to be more granular than
* pg_dist_node, scoping only for modifications on the replicated
* tables. However, we currently do not have any such mechanism and
* given that citus_disable_node() runs instantly, it seems acceptable
* to block reads (or modifications on non-replicated tables) for
* a while.
*/
/* only superuser can disable node */
Assert(superuser());
SendCommandToWorkersWithMetadata(
"LOCK TABLE pg_catalog.pg_dist_node IN EXCLUSIVE MODE;");
}
/*
* master_disable_node is a wrapper function for old UDF name.
*/
Datum
master_disable_node(PG_FUNCTION_ARGS)
{
return citus_disable_node(fcinfo);
}
/*
* citus_set_node_property sets a property of the node
*/
Datum
citus_set_node_property(PG_FUNCTION_ARGS)
{
text *nodeNameText = PG_GETARG_TEXT_P(0);
int32 nodePort = PG_GETARG_INT32(1);
text *propertyText = PG_GETARG_TEXT_P(2);
bool value = PG_GETARG_BOOL(3);
WorkerNode *workerNode = ModifiableWorkerNode(text_to_cstring(nodeNameText),
nodePort);
/*
* We do not allow metadata operations on secondary nodes in nontransactional
* sync mode.
*/
if (NodeIsSecondary(workerNode))
{
EnsureTransactionalMetadataSyncMode();
}
if (strcmp(text_to_cstring(propertyText), "shouldhaveshards") == 0)
{
SetShouldHaveShards(workerNode, value);
}
else
{
ereport(ERROR, (errmsg(
"only the 'shouldhaveshards' property can be set using this function")));
}
TransactionModifiedNodeMetadata = true;
PG_RETURN_VOID();
}
/*
* master_set_node_property is a wrapper function for old UDF name.
*/
Datum
master_set_node_property(PG_FUNCTION_ARGS)
{
return citus_set_node_property(fcinfo);
}
/*
* ModifiableWorkerNode gets the requested WorkerNode and also gets locks
* required for modifying it. This fails if the node does not exist.
*/
WorkerNode *
ModifiableWorkerNode(const char *nodeName, int32 nodePort)
{
CheckCitusVersion(ERROR);
EnsureCoordinator();
/* take an exclusive lock on pg_dist_node to serialize pg_dist_node changes */
LockRelationOid(DistNodeRelationId(), ExclusiveLock);
WorkerNode *workerNode = FindWorkerNodeAnyCluster(nodeName, nodePort);
if (workerNode == NULL)
{
ereport(ERROR, (errmsg("node at \"%s:%u\" does not exist", nodeName, nodePort)));
}
return workerNode;
}
/*
* citus_activate_node UDF activates the given node. It sets the node's isactive
* value to active and replicates all reference tables to that node.
*/
Datum
citus_activate_node(PG_FUNCTION_ARGS)
{
text *nodeNameText = PG_GETARG_TEXT_P(0);
int32 nodePort = PG_GETARG_INT32(1);
char *nodeNameString = text_to_cstring(nodeNameText);
WorkerNode *workerNode = ModifiableWorkerNode(nodeNameString, nodePort);
/*
* We do not allow metadata operations on secondary nodes in nontransactional
* sync mode.
*/
if (NodeIsSecondary(workerNode))
{
EnsureTransactionalMetadataSyncMode();
}
/*
* Create MetadataSyncContext which is used throughout nodes' activation.
* It contains activated nodes, bare connections if the mode is nontransactional,
* and a memory context for allocation.
*/
bool collectCommands = false;
bool nodesAddedInSameTransaction = false;
MetadataSyncContext *context = CreateMetadataSyncContext(list_make1(workerNode),
collectCommands,
nodesAddedInSameTransaction);
ActivateNodeList(context);
TransactionModifiedNodeMetadata = true;
PG_RETURN_INT32(workerNode->nodeId);
}
/*
* master_activate_node is a wrapper function for old UDF name.
*/
Datum
master_activate_node(PG_FUNCTION_ARGS)
{
return citus_activate_node(fcinfo);
}
/*
* GroupForNode returns the group which a given node belongs to.
*
* It only works if the requested node is a part of CurrentCluster.
*/
uint32
GroupForNode(char *nodeName, int nodePort)
{
WorkerNode *workerNode = FindWorkerNode(nodeName, nodePort);
if (workerNode == NULL)
{
ereport(ERROR, (errmsg("node at \"%s:%u\" does not exist", nodeName, nodePort)));
}
return workerNode->groupId;
}
/*
* NodeIsPrimaryAndRemote returns whether the argument represents the remote
* primary node.
*/
bool
NodeIsPrimaryAndRemote(WorkerNode *worker)
{
return NodeIsPrimary(worker) && !NodeIsLocal(worker);
}
/*
* NodeIsPrimary returns whether the argument represents a primary node.
*/
bool
NodeIsPrimary(WorkerNode *worker)
{
Oid primaryRole = PrimaryNodeRoleId();
/* if nodeRole does not yet exist, all nodes are primary nodes */
if (primaryRole == InvalidOid)
{
return true;
}
return worker->nodeRole == primaryRole;
}
/*
* NodeIsLocal returns whether the argument represents the local node.
*/
static bool
NodeIsLocal(WorkerNode *worker)
{
return worker->groupId == GetLocalGroupId();
}
/*
* NodeIsSecondary returns whether the argument represents a secondary node.
*/
bool
NodeIsSecondary(WorkerNode *worker)
{
Oid secondaryRole = SecondaryNodeRoleId();
/* if nodeRole does not yet exist, all nodes are primary nodes */
if (secondaryRole == InvalidOid)
{
return false;
}
return worker->nodeRole == secondaryRole;
}
/*
* NodeIsReadable returns whether we're allowed to send SELECT queries to this
* node.
*/
bool
NodeIsReadable(WorkerNode *workerNode)
{
if (ReadFromSecondaries == USE_SECONDARY_NODES_NEVER &&
NodeIsPrimary(workerNode))
{
return true;
}
if (ReadFromSecondaries == USE_SECONDARY_NODES_ALWAYS &&
NodeIsSecondary(workerNode))
{
return true;
}
return false;
}
/*
* PrimaryNodeForGroup returns the (unique) primary in the specified group.
*
* If there are any nodes in the requested group and groupContainsNodes is not NULL
* it will set the bool groupContainsNodes references to true.
*/
WorkerNode *
PrimaryNodeForGroup(int32 groupId, bool *groupContainsNodes)
{
WorkerNode *workerNode = NULL;
HASH_SEQ_STATUS status;
HTAB *workerNodeHash = GetWorkerNodeHash();
hash_seq_init(&status, workerNodeHash);
while ((workerNode = hash_seq_search(&status)) != NULL)
{
int32 workerNodeGroupId = workerNode->groupId;
if (workerNodeGroupId != groupId)
{
continue;
}
if (groupContainsNodes != NULL)
{
*groupContainsNodes = true;
}
if (NodeIsPrimary(workerNode))
{
hash_seq_term(&status);
return workerNode;
}
}
return NULL;
}
/*
* MarkNodesNotSyncedInLoopBackConnection unsets metadatasynced flag in separate
* connection to localhost by calling the udf `citus_internal_mark_node_not_synced`.
*/
static void
MarkNodesNotSyncedInLoopBackConnection(MetadataSyncContext *context,
pid_t parentSessionPid)
{
Assert(context->transactionMode == METADATA_SYNC_NON_TRANSACTIONAL);
Assert(!MetadataSyncCollectsCommands(context));
/*
* Set metadatasynced to false for all activated nodes to mark the nodes as not synced
* in case nontransactional metadata sync fails before we activate the nodes inside
* metadataSyncContext.
* We set metadatasynced to false at coordinator to mark the nodes as not synced. But we
* do not set isactive and hasmetadata flags to false as we still want to route queries
* to the nodes if their isactive flag is true and propagate DDL to the nodes if possible.
*
* NOTES:
* 1) We use separate connection to localhost as we would rollback the local
* transaction in case of failure.
* 2) Operator should handle problems at workers if any. Wworkers probably fail
* due to improper metadata when a query hits. Or DDL might fail due to desynced
* nodes. (when hasmetadata = true, metadatasynced = false)
* In those cases, proper metadata sync for the workers should be done.)
*/
/*
* Because we try to unset metadatasynced flag with a separate transaction,
* we could not find the new node if the node is added in the current local
* transaction. But, hopefully, we do not need to unset metadatasynced for
* the new node as local transaction would rollback in case of a failure.
*/
if (context->nodesAddedInSameTransaction)
{
return;
}
if (context->activatedWorkerNodeList == NIL)
{
return;
}
int connectionFlag = FORCE_NEW_CONNECTION;
MultiConnection *connection = GetNodeConnection(connectionFlag, LocalHostName,
PostPortNumber);
List *commandList = NIL;
WorkerNode *workerNode = NULL;
foreach_ptr(workerNode, context->activatedWorkerNodeList)
{
/*
* We need to prevent self deadlock when we access pg_dist_node using separate
* connection to localhost. To achieve this, we check if the caller session's
* pid holds the Exclusive lock on pg_dist_node. After ensuring that (we are
* called from parent session which holds the Exclusive lock), we can safely
* update node metadata by acquiring the relaxed lock.
*/
StringInfo metadatasyncCommand = makeStringInfo();
appendStringInfo(metadatasyncCommand, CITUS_INTERNAL_MARK_NODE_NOT_SYNCED,
parentSessionPid, workerNode->nodeId);
commandList = lappend(commandList, metadatasyncCommand->data);
}
SendCommandListToWorkerOutsideTransactionWithConnection(connection, commandList);
CloseConnection(connection);
}