forked from apache/cloudberry
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcdbutil.c
More file actions
4216 lines (3567 loc) · 107 KB
/
Copy pathcdbutil.c
File metadata and controls
4216 lines (3567 loc) · 107 KB
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
/*-------------------------------------------------------------------------
*
* cdbutil.c
* Internal utility support functions for Apache Cloudberry/PostgreSQL.
*
* Portions Copyright (c) 2005-2011, Greenplum inc
* Portions Copyright (c) 2012-Present VMware, Inc. or its affiliates.
*
*
* IDENTIFICATION
* src/backend/cdb/cdbutil.c
*
* NOTES
*
* - According to src/backend/executor/execHeapScan.c
* "tuples returned by heap_getnext() are pointers onto disk
* pages and were not created with palloc() and so should not
* be pfree()'d"
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/time.h>
#include <sys/resource.h>
#endif
#include <sys/param.h> /* for MAXHOSTNAMELEN */
#include "access/genam.h"
#include "common/ip.h"
#include "nodes/makefuncs.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/memutils.h"
#include "catalog/gp_id.h"
#include "catalog/indexing.h"
#include "cdb/cdbhash.h"
#include "cdb/cdbutil.h"
#include "cdb/cdbmotion.h"
#include "cdb/cdbvars.h"
#include "cdb/cdbgang.h"
#include "cdb/cdbdisp_query.h"
#include "cdb/ml_ipc.h" /* listener_setup */
#include "cdb/cdbtm.h"
#include "libpq-fe.h"
#include "libpq-int.h"
#include "cdb/cdbconn.h"
#include "cdb/cdbfts.h"
#include "storage/ipc.h"
#include "storage/proc.h"
#include "postmaster/fts.h"
#include "postmaster/postmaster.h"
#include "catalog/namespace.h"
#include "utils/gpexpand.h"
#include "access/xact.h"
#include "common/hashfn.h"
#include "catalog/gp_indexing.h"
#include "utils/etcd.h"
#include "common/etcdutils.h"
#include "catalog/gp_indexing.h"
#define MAX_CACHED_1_GANGS 1
#define INCR_COUNT(cdbinfo, arg) \
(cdbinfo)->arg++; \
(cdbinfo)->cdbs->arg++;
#define DECR_COUNT(cdbinfo, arg) \
(cdbinfo)->arg--; \
(cdbinfo)->cdbs->arg--; \
Assert((cdbinfo)->arg >= 0); \
Assert((cdbinfo)->cdbs->arg >= 0); \
#define GPSEGCONFIGDUMPFILE "gpsegconfig_dump"
#define GPSEGCONFIGDUMPFILETMP "gpsegconfig_dump_tmp"
MemoryContext CdbComponentsContext = NULL;
static CdbComponentDatabases *cdb_component_dbs = NULL;
#ifdef USE_INTERNAL_FTS
/*
* Helper Functions
*/
static CdbComponentDatabases *getCdbComponentInfo(void);
static void cleanupComponentIdleQEs(CdbComponentDatabaseInfo *cdi, bool includeWriter);
static int CdbComponentDatabaseInfoCompare(const void *p1, const void *p2);
static GpSegConfigEntry * readGpSegConfigFromCatalog(int *total_dbs);
static GpSegConfigEntry * readGpSegConfigFromFTSFiles(int *total_dbs);
static void getAddressesForDBid(GpSegConfigEntry *c, int elevel);
static HTAB *hostPrimaryCountHashTableInit(void);
static int nextQEIdentifer(CdbComponentDatabases *cdbs);
Datum gp_get_suboverflowed_backends(PG_FUNCTION_ARGS);
static HTAB *segment_ip_cache_htab = NULL;
int numsegmentsFromQD = -1;
typedef struct SegIpEntry
{
char key[NAMEDATALEN];
char hostinfo[NI_MAXHOST];
} SegIpEntry;
typedef struct HostPrimaryCountEntry
{
char hostname[MAXHOSTNAMELEN];
int segmentCount;
} HostPrimaryCountEntry;
/*
* Helper functions for fetching latest gp_segment_configuration outside of
* the transaction.
*
* In phase 2 of 2PC, current xact has been marked to TRANS_COMMIT/ABORT,
* COMMIT_PREPARED or ABORT_PREPARED DTM are performed, if they failed,
* dispatcher disconnect and destroy all gangs and fetch the latest segment
* configurations to do RETRY_COMMIT_PREPARED or RETRY_ABORT_PREPARED,
* however, postgres disallow catalog lookups outside of xacts.
*
* readGpSegConfigFromFTSFiles() notify FTS to dump the configs from catalog
* to a flat file and then read configurations from that file.
*/
static GpSegConfigEntry *
readGpSegConfigFromFTSFiles(int *total_dbs)
{
FILE *fd;
int idx = 0;
int array_size = 500;
GpSegConfigEntry *configs = NULL;
GpSegConfigEntry *config = NULL;
char hostname[MAXHOSTNAMELEN];
char address[MAXHOSTNAMELEN];
char buf[MAXHOSTNAMELEN * 2 + 32];
Assert(!IsTransactionState());
/* notify and wait FTS to finish a probe and update the dump file */
FtsNotifyProber();
fd = AllocateFile(GPSEGCONFIGDUMPFILE, "r");
if (!fd)
elog(ERROR, "could not open gp_segment_configutation dump file:%s:%m", GPSEGCONFIGDUMPFILE);
configs = palloc0(sizeof (GpSegConfigEntry) * array_size);
while (fgets(buf, sizeof(buf), fd))
{
config = &configs[idx];
if (sscanf(buf, "%d %d %c %c %c %c %d %s %s", (int *)&config->dbid, (int *)&config->segindex,
&config->role, &config->preferred_role, &config->mode, &config->status,
&config->port, hostname, address) != GPSEGCONFIGNUMATTR)
{
FreeFile(fd);
elog(ERROR, "invalid data in gp_segment_configuration dump file: %s:%m", GPSEGCONFIGDUMPFILE);
}
config->hostname = pstrdup(hostname);
config->address = pstrdup(address);
idx++;
/*
* Expand CdbComponentDatabaseInfo array if we've used up
* currently allocated space
*/
if (idx >= array_size)
{
array_size = array_size * 2;
configs = (GpSegConfigEntry *)
repalloc(configs, sizeof(GpSegConfigEntry) * array_size);
}
}
FreeFile(fd);
*total_dbs = idx;
return configs;
}
/*
* writeGpSegConfigToFTSFiles() dump gp_segment_configuration to the file
* GPSEGCONFIGDUMPFILE, in $PGDATA, only FTS process can use this function.
*
* write contents to GPSEGCONFIGDUMPFILETMP first, then rename it to
* GPSEGCONFIGDUMPFILE, it makes lockless read and write concurrently.
*/
void
writeGpSegConfigToFTSFiles(void)
{
FILE *fd;
int idx = 0;
int total_dbs = 0;
GpSegConfigEntry *configs = NULL;
GpSegConfigEntry *config = NULL;
Assert(IsTransactionState());
Assert(am_ftsprobe);
fd = AllocateFile(GPSEGCONFIGDUMPFILETMP, "w+");
if (!fd)
elog(ERROR, "could not create tmp file: %s: %m", GPSEGCONFIGDUMPFILETMP);
configs = readGpSegConfigFromCatalog(&total_dbs);
for (idx = 0; idx < total_dbs; idx++)
{
config = &configs[idx];
if (fprintf(fd, "%d %d %c %c %c %c %d %s %s\n", config->dbid, config->segindex,
config->role, config->preferred_role, config->mode, config->status,
config->port, config->hostname, config->address) < 0)
{
FreeFile(fd);
elog(ERROR, "could not dump gp_segment_configuration to file: %s: %m", GPSEGCONFIGDUMPFILE);
}
}
FreeFile(fd);
/* rename tmp file to permanent file */
if (rename(GPSEGCONFIGDUMPFILETMP, GPSEGCONFIGDUMPFILE) != 0)
elog(ERROR, "could not rename file %s to file %s: %m",
GPSEGCONFIGDUMPFILETMP, GPSEGCONFIGDUMPFILE);
}
static GpSegConfigEntry *
readGpSegConfigFromCatalog(int *total_dbs)
{
int idx = 0;
int array_size;
bool isNull;
Datum attr;
Oid warehouseid = InvalidOid;
Relation gp_seg_config_rel;
HeapTuple gp_seg_config_tuple = NULL;
SysScanDesc gp_seg_config_scan;
GpSegConfigEntry *configs;
GpSegConfigEntry *config;
array_size = 500;
configs = palloc0(sizeof(GpSegConfigEntry) * array_size);
gp_seg_config_rel = table_open(GpSegmentConfigRelationId, AccessShareLock);
gp_seg_config_scan = systable_beginscan(gp_seg_config_rel, InvalidOid, false, NULL,
0, NULL);
while (HeapTupleIsValid(gp_seg_config_tuple = systable_getnext(gp_seg_config_scan)))
{
/* warehouseid */
attr = heap_getattr(gp_seg_config_tuple, Anum_gp_segment_configuration_warehouseid, RelationGetDescr(gp_seg_config_rel), &isNull);
Assert(!isNull);
warehouseid = DatumGetObjectId(attr);
/* content */
attr = heap_getattr(gp_seg_config_tuple, Anum_gp_segment_configuration_content, RelationGetDescr(gp_seg_config_rel), &isNull);
Assert(!isNull);
if (warehouseid == GetCurrentWarehouseId() || DatumGetInt16(attr) == MASTER_CONTENT_ID)
{
config = &configs[idx];
/* dbid */
attr = heap_getattr(gp_seg_config_tuple, Anum_gp_segment_configuration_dbid, RelationGetDescr(gp_seg_config_rel), &isNull);
Assert(!isNull);
config->dbid = DatumGetInt16(attr);
/* content */
attr = heap_getattr(gp_seg_config_tuple, Anum_gp_segment_configuration_content, RelationGetDescr(gp_seg_config_rel), &isNull);
Assert(!isNull);
config->segindex= DatumGetInt16(attr);
/* role */
attr = heap_getattr(gp_seg_config_tuple, Anum_gp_segment_configuration_role, RelationGetDescr(gp_seg_config_rel), &isNull);
Assert(!isNull);
config->role = DatumGetChar(attr);
/* preferred-role */
attr = heap_getattr(gp_seg_config_tuple, Anum_gp_segment_configuration_preferred_role, RelationGetDescr(gp_seg_config_rel), &isNull);
Assert(!isNull);
config->preferred_role = DatumGetChar(attr);
/* mode */
attr = heap_getattr(gp_seg_config_tuple, Anum_gp_segment_configuration_mode, RelationGetDescr(gp_seg_config_rel), &isNull);
Assert(!isNull);
config->mode = DatumGetChar(attr);
/* status */
attr = heap_getattr(gp_seg_config_tuple, Anum_gp_segment_configuration_status, RelationGetDescr(gp_seg_config_rel), &isNull);
Assert(!isNull);
config->status = DatumGetChar(attr);
/* hostname */
attr = heap_getattr(gp_seg_config_tuple, Anum_gp_segment_configuration_hostname, RelationGetDescr(gp_seg_config_rel), &isNull);
Assert(!isNull);
config->hostname = TextDatumGetCString(attr);
/* address */
attr = heap_getattr(gp_seg_config_tuple, Anum_gp_segment_configuration_address, RelationGetDescr(gp_seg_config_rel), &isNull);
Assert(!isNull);
config->address = TextDatumGetCString(attr);
/* port */
attr = heap_getattr(gp_seg_config_tuple, Anum_gp_segment_configuration_port, RelationGetDescr(gp_seg_config_rel), &isNull);
Assert(!isNull);
config->port = DatumGetInt32(attr);
/* datadir is not dumped*/
idx++;
/*
* Expand CdbComponentDatabaseInfo array if we've used up
* currently allocated space
*/
if (idx >= array_size)
{
array_size = array_size * 2;
configs = (GpSegConfigEntry *)
repalloc(configs, sizeof(GpSegConfigEntry) * array_size);
}
}
}
/*
* We're done with the catalog config, clean them up, closing all the
* relations we opened.
*/
systable_endscan(gp_seg_config_scan);
table_close(gp_seg_config_rel, AccessShareLock);
*total_dbs = idx;
return configs;
}
/*
* Internal function to initialize each component info
*/
static CdbComponentDatabases *
getCdbComponentInfo(void)
{
MemoryContext oldContext;
CdbComponentDatabaseInfo *cdbInfo;
CdbComponentDatabases *component_databases = NULL;
GpSegConfigEntry *configs;
int i;
int x = 0;
int total_dbs = 0;
bool found;
HostPrimaryCountEntry *hsEntry;
if (!CdbComponentsContext)
CdbComponentsContext = AllocSetContextCreate(TopMemoryContext, "cdb components Context",
ALLOCSET_DEFAULT_MINSIZE,
ALLOCSET_DEFAULT_INITSIZE,
ALLOCSET_DEFAULT_MAXSIZE);
oldContext = MemoryContextSwitchTo(CdbComponentsContext);
HTAB *hostPrimaryCountHash = hostPrimaryCountHashTableInit();
if (IsTransactionState())
configs = readGpSegConfigFromCatalog(&total_dbs);
else
configs = readGpSegConfigFromFTSFiles(&total_dbs);
component_databases = palloc0(sizeof(CdbComponentDatabases));
component_databases->numActiveQEs = 0;
component_databases->numIdleQEs = 0;
component_databases->qeCounter = 0;
component_databases->freeCounterList = NIL;
component_databases->segment_db_info =
(CdbComponentDatabaseInfo *) palloc0(sizeof(CdbComponentDatabaseInfo) * total_dbs);
component_databases->entry_db_info =
(CdbComponentDatabaseInfo *) palloc0(sizeof(CdbComponentDatabaseInfo) * 2);
for (i = 0; i < total_dbs; i++)
{
CdbComponentDatabaseInfo *pRow;
GpSegConfigEntry *config = &configs[i];
if (config->hostname == NULL || strlen(config->hostname) > MAXHOSTNAMELEN)
{
/*
* We should never reach here, but add sanity check
* The reason we check length is we find MAXHOSTNAMELEN might be
* smaller than the ones defined in /etc/hosts. Those are rare cases.
*/
elog(ERROR,
"Invalid length (%d) of hostname (%s)",
config->hostname == NULL ? 0 : (int) strlen(config->hostname),
config->hostname == NULL ? "" : config->hostname);
}
/* lookup hostip/hostaddrs cache */
config->hostip= NULL;
getAddressesForDBid(config, !am_ftsprobe? ERROR : LOG);
/*
* We make sure we get a valid hostip for primary here,
* if hostip for mirrors can not be get, ignore the error.
*/
if (config->hostaddrs[0] == NULL &&
config->role == GP_SEGMENT_CONFIGURATION_ROLE_PRIMARY)
ereport(!am_ftsprobe ? ERROR : LOG,
(errcode(ERRCODE_CONNECTION_FAILURE),
errmsg("cannot resolve network address for dbid=%d", config->dbid)));
if (config->hostaddrs[0] != NULL)
config->hostip = pstrdup(config->hostaddrs[0]);
AssertImply(config->hostip, strlen(config->hostip) <= INET6_ADDRSTRLEN);
/*
* Determine which array to place this rows data in: entry or segment,
* based on the content field.
*/
if (config->segindex >= 0)
{
pRow = &component_databases->segment_db_info[component_databases->total_segment_dbs];
component_databases->total_segment_dbs++;
}
else
{
pRow = &component_databases->entry_db_info[component_databases->total_entry_dbs];
component_databases->total_entry_dbs++;
}
pRow->cdbs = component_databases;
pRow->config = config;
pRow->freelist = NIL;
pRow->activelist = NIL;
pRow->numIdleQEs = 0;
pRow->numActiveQEs = 0;
if (config->role != GP_SEGMENT_CONFIGURATION_ROLE_PRIMARY)
continue;
hsEntry = (HostPrimaryCountEntry *) hash_search(hostPrimaryCountHash, config->hostname, HASH_ENTER, &found);
if (found)
hsEntry->segmentCount++;
else
hsEntry->segmentCount = 1;
}
/*
* Validate that there exists at least one entry and one segment database
* in the configuration
*/
/*
* In singlenode deployment, total_segment_dbs is zero and it should still work.
*/
if (component_databases->total_segment_dbs == 0 && !IS_SINGLENODE())
{
ereport(ERROR,
(errcode(ERRCODE_CARDINALITY_VIOLATION),
errmsg("number of segment databases cannot be 0")));
}
if (component_databases->total_entry_dbs == 0)
{
ereport(ERROR,
(errcode(ERRCODE_CARDINALITY_VIOLATION),
errmsg("number of entry databases cannot be 0")));
}
/*
* Now sort the data by segindex, isprimary desc
*/
qsort(component_databases->segment_db_info,
component_databases->total_segment_dbs, sizeof(CdbComponentDatabaseInfo),
CdbComponentDatabaseInfoCompare);
qsort(component_databases->entry_db_info,
component_databases->total_entry_dbs, sizeof(CdbComponentDatabaseInfo),
CdbComponentDatabaseInfoCompare);
/*
* Now count the number of distinct segindexes. Since it's sorted, this is
* easy.
*/
for (i = 0; i < component_databases->total_segment_dbs; i++)
{
if (i == 0 ||
(component_databases->segment_db_info[i].config->segindex != component_databases->segment_db_info[i - 1].config->segindex))
{
component_databases->total_segments++;
}
}
/*
* Now validate that our identity is present in the entry databases
*/
for (i = 0; i < component_databases->total_entry_dbs; i++)
{
cdbInfo = &component_databases->entry_db_info[i];
if (cdbInfo->config->dbid == GpIdentity.dbid && cdbInfo->config->segindex == GpIdentity.segindex)
{
break;
}
}
if (i == component_databases->total_entry_dbs)
{
ereport(ERROR,
(errcode(ERRCODE_DATA_EXCEPTION),
errmsg("cannot locate entry database"),
errdetail("Entry database represented by this db in gp_segment_configuration: dbid %d content %d",
GpIdentity.dbid, GpIdentity.segindex)));
}
/*
* Now validate that the segindexes for the segment databases are between
* 0 and (numsegments - 1) inclusive, and that we hit them all.
* Since it's sorted, this is relatively easy.
*/
x = 0;
for (i = 0; i < component_databases->total_segments; i++)
{
int this_segindex = -1;
while (x < component_databases->total_segment_dbs)
{
this_segindex = component_databases->segment_db_info[x].config->segindex;
if (this_segindex < i)
x++;
else if (this_segindex == i)
break;
else if (this_segindex > i)
{
ereport(ERROR,
(errcode(ERRCODE_DATA_EXCEPTION),
errmsg("content values not valid in %s table",
GpSegmentConfigRelationName),
errdetail("Content values must be in the range 0 to %d inclusive.",
component_databases->total_segments - 1)));
}
}
if (this_segindex != i)
{
ereport(ERROR,
(errcode(ERRCODE_DATA_EXCEPTION),
errmsg("content values not valid in %s table",
GpSegmentConfigRelationName),
errdetail("Content values must be in the range 0 to %d inclusive",
component_databases->total_segments - 1)));
}
}
for (i = 0; i < component_databases->total_segment_dbs; i++)
{
cdbInfo = &component_databases->segment_db_info[i];
if (!IS_HOT_STANDBY_QD() && cdbInfo->config->role != GP_SEGMENT_CONFIGURATION_ROLE_PRIMARY)
continue;
hsEntry = (HostPrimaryCountEntry *) hash_search(hostPrimaryCountHash, cdbInfo->config->hostname, HASH_FIND, &found);
Assert(found);
cdbInfo->hostPrimaryCount = hsEntry->segmentCount;
}
for (i = 0; i < component_databases->total_entry_dbs; i++)
{
cdbInfo = &component_databases->entry_db_info[i];
if (!IS_HOT_STANDBY_QD() && cdbInfo->config->role != GP_SEGMENT_CONFIGURATION_ROLE_PRIMARY)
continue;
hsEntry = (HostPrimaryCountEntry *) hash_search(hostPrimaryCountHash, cdbInfo->config->hostname, HASH_FIND, &found);
Assert(found);
cdbInfo->hostPrimaryCount = hsEntry->segmentCount;
}
hash_destroy(hostPrimaryCountHash);
MemoryContextSwitchTo(oldContext);
return component_databases;
}
/*
* Helper function to clean up the idle segdbs list of
* a segment component.
*/
static void
cleanupComponentIdleQEs(CdbComponentDatabaseInfo *cdi, bool includeWriter)
{
SegmentDatabaseDescriptor *segdbDesc;
MemoryContext oldContext;
ListCell *curItem;
Assert(CdbComponentsContext);
oldContext = MemoryContextSwitchTo(CdbComponentsContext);
curItem = list_head(cdi->freelist);
foreach(curItem, cdi->freelist)
{
segdbDesc = (SegmentDatabaseDescriptor *)lfirst(curItem);
Assert(segdbDesc);
if (segdbDesc->isWriter && !includeWriter)
continue;
cdi->freelist = foreach_delete_current(cdi->freelist, curItem);
DECR_COUNT(cdi, numIdleQEs);
cdbconn_termSegmentDescriptor(segdbDesc);
}
MemoryContextSwitchTo(oldContext);
}
void
cdbcomponent_cleanupIdleQEs(bool includeWriter)
{
CdbComponentDatabases *cdbs;
int i;
/* use cdb_component_dbs directly */
cdbs = cdb_component_dbs;
if (cdbs == NULL)
return;
if (cdbs->segment_db_info != NULL)
{
for (i = 0; i < cdbs->total_segment_dbs; i++)
{
CdbComponentDatabaseInfo *cdi = &cdbs->segment_db_info[i];
cleanupComponentIdleQEs(cdi, includeWriter);
}
}
if (cdbs->entry_db_info != NULL)
{
for (i = 0; i < cdbs->total_entry_dbs; i++)
{
CdbComponentDatabaseInfo *cdi = &cdbs->entry_db_info[i];
cleanupComponentIdleQEs(cdi, includeWriter);
}
}
return;
}
/*
* This function is called when a transaction is started and the snapshot of
* segments info will not changed until the end of transaction
*/
void
cdbcomponent_updateCdbComponents(void)
{
uint8 ftsVersion= getFtsVersion();
int expandVersion = GetGpExpandVersion();
/*
* FTS takes responsibility for updating gp_segment_configuration, in each
* fts probe cycle, FTS firstly gets a copy of current configuration, then
* probe the segments based on it and finally free the copy in the end. In
* the probe stage, FTS might start/close transactions many times, so FTS
* should not update current copy of gp_segment_configuration when a new
* transaction is started.
*/
if (am_ftsprobe)
return;
PG_TRY();
{
if (cdb_component_dbs == NULL)
{
cdb_component_dbs = getCdbComponentInfo();
cdb_component_dbs->fts_version = ftsVersion;
cdb_component_dbs->expand_version = GetGpExpandVersion();
}
else if ((cdb_component_dbs->fts_version != ftsVersion ||
cdb_component_dbs->expand_version != expandVersion))
{
if (TempNamespaceOidIsValid())
{
/*
* Do not update here, otherwise, temp files will be lost
* in segments;
*/
}
else
{
ELOG_DISPATCHER_DEBUG("FTS rescanned, get new component databases info.");
cdbcomponent_destroyCdbComponents();
cdb_component_dbs = getCdbComponentInfo();
cdb_component_dbs->fts_version = ftsVersion;
cdb_component_dbs->expand_version = expandVersion;
}
}
}
PG_CATCH();
{
FtsNotifyProber();
PG_RE_THROW();
}
PG_END_TRY();
Assert(cdb_component_dbs->numActiveQEs == 0);
}
/*
* cdbcomponent_getCdbComponents
*
*
* Storage for the SegmentInstances block and all subsidiary
* structures are allocated from the caller's context.
*/
CdbComponentDatabases *
cdbcomponent_getCdbComponents()
{
PG_TRY();
{
if (cdb_component_dbs == NULL)
{
cdb_component_dbs = getCdbComponentInfo();
cdb_component_dbs->fts_version = getFtsVersion();
cdb_component_dbs->expand_version = GetGpExpandVersion();
}
}
PG_CATCH();
{
if (Gp_role == GP_ROLE_DISPATCH)
FtsNotifyProber();
PG_RE_THROW();
}
PG_END_TRY();
return cdb_component_dbs;
}
/*
* cdbcomponet_destroyCdbComponents
*
* Disconnect and destroy all idle QEs, releases the memory
* occupied by the CdbComponentDatabases
*
* callers must clean up QEs used by dispatcher states.
*/
void
cdbcomponent_destroyCdbComponents(void)
{
/* caller must clean up all segdbs used by dispatcher states */
Assert(!cdbcomponent_activeQEsExist());
hash_destroy(segment_ip_cache_htab);
segment_ip_cache_htab = NULL;
/* disconnect and destroy idle QEs include writers */
cdbcomponent_cleanupIdleQEs(true);
/* delete the memory context */
if (CdbComponentsContext)
MemoryContextDelete(CdbComponentsContext);
CdbComponentsContext = NULL;
cdb_component_dbs = NULL;
}
/*
* Allocated a segdb
*
* If there is idle segdb in the freelist, return it, otherwise, initialize
* a new segdb.
*
* idle segdbs has an established connection with segment, but new segdb is
* not setup yet, callers need to establish the connection by themselves.
*/
SegmentDatabaseDescriptor *
cdbcomponent_allocateIdleQE(int contentId, SegmentType segmentType)
{
SegmentDatabaseDescriptor *segdbDesc = NULL;
CdbComponentDatabaseInfo *cdbinfo;
ListCell *curItem;
MemoryContext oldContext;
bool isWriter;
cdbinfo = cdbcomponent_getComponentInfo(contentId);
oldContext = MemoryContextSwitchTo(CdbComponentsContext);
/*
* Always try to pop from the head. Make sure to push them back to head
* in cdbcomponent_recycleIdleQE().
*/
foreach(curItem, cdbinfo->freelist)
{
SegmentDatabaseDescriptor *tmp =
(SegmentDatabaseDescriptor *)lfirst(curItem);
Assert(tmp);
if ((segmentType == SEGMENTTYPE_EXPLICT_WRITER && !tmp->isWriter) ||
(segmentType == SEGMENTTYPE_EXPLICT_READER && tmp->isWriter))
continue;
cdbinfo->freelist = foreach_delete_current(cdbinfo->freelist, curItem);
/* update numIdleQEs */
DECR_COUNT(cdbinfo, numIdleQEs);
segdbDesc = tmp;
break;
}
if (!segdbDesc)
{
/*
* 1. for entrydb, it's never be writer.
* 2. for first QE, it must be a writer.
*/
isWriter = contentId == -1 ? false: (cdbinfo->numIdleQEs == 0 && cdbinfo->numActiveQEs == 0);
segdbDesc = cdbconn_createSegmentDescriptor(cdbinfo, nextQEIdentifer(cdbinfo->cdbs), isWriter);
}
cdbconn_setQEIdentifier(segdbDesc, -1);
cdbinfo->activelist = lcons(segdbDesc, cdbinfo->activelist);
INCR_COUNT(cdbinfo, numActiveQEs);
MemoryContextSwitchTo(oldContext);
return segdbDesc;
}
static bool
cleanupQE(SegmentDatabaseDescriptor *segdbDesc)
{
Assert(segdbDesc != NULL);
#ifdef FAULT_INJECTOR
if (SIMPLE_FAULT_INJECTOR("cleanup_qe") == FaultInjectorTypeSkip)
return false;
#endif
/*
* if the process is in the middle of blowing up... then we don't do
* anything here. making libpq and other calls can definitely result in
* things getting HUNG.
*/
if (proc_exit_inprogress)
return false;
if (cdbconn_isBadConnection(segdbDesc))
return false;
/* if segment is down, the gang can not be reused */
if (FtsIsSegmentDown(segdbDesc->segment_database_info))
return false;
/* If a reader exceed the cached memory limitation, destroy it */
if (!segdbDesc->isWriter &&
(segdbDesc->conn->mop_high_watermark >> 20) > gp_vmem_protect_gang_cache_limit)
return false;
/* Note, we cancel all "still running" queries */
if (!cdbconn_discardResults(segdbDesc, 20))
{
elog(LOG, "cleaning up seg%d while it is still busy", segdbDesc->segindex);
return false;
}
/* QE is no longer associated with a slice. */
cdbconn_setQEIdentifier(segdbDesc, /* slice index */ -1);
return true;
}
void
cdbcomponent_recycleIdleQE(SegmentDatabaseDescriptor *segdbDesc, bool forceDestroy)
{
CdbComponentDatabaseInfo *cdbinfo;
MemoryContext oldContext;
int maxLen;
bool isWriter;
Assert(cdb_component_dbs);
Assert(CdbComponentsContext);
cdbinfo = segdbDesc->segment_database_info;
isWriter = segdbDesc->isWriter;
/* update num of active QEs */
Assert(list_member_ptr(cdbinfo->activelist, segdbDesc));
cdbinfo->activelist = list_delete_ptr(cdbinfo->activelist, segdbDesc);
DECR_COUNT(cdbinfo, numActiveQEs);
oldContext = MemoryContextSwitchTo(CdbComponentsContext);
if (forceDestroy || !cleanupQE(segdbDesc))
goto destroy_segdb;
/* If freelist length exceed gp_cached_gang_threshold, destroy it */
maxLen = segdbDesc->segindex == -1 ?
MAX_CACHED_1_GANGS : gp_cached_gang_threshold;
if (!isWriter && list_length(cdbinfo->freelist) >= maxLen)
goto destroy_segdb;
/* Recycle the QE, put it to freelist */
if (isWriter)
{
/* writer is always the header of freelist */
segdbDesc->segment_database_info->freelist =
lcons(segdbDesc, segdbDesc->segment_database_info->freelist);
}
else
{
int lastWriterPos = -1;
ListCell *cell;
/*
* In cdbcomponent_allocateIdleQE() readers are always popped from the
* head, so to restore the original order we must pushed them back to
* the head, and keep in mind readers must be put after the writers.
*/
for (cell = list_head(segdbDesc->segment_database_info->freelist);
cell && ((SegmentDatabaseDescriptor *) lfirst(cell))->isWriter;
lastWriterPos++, cell = lnext(segdbDesc->segment_database_info->freelist, cell)) ;
if (lastWriterPos >= 0)
segdbDesc->segment_database_info->freelist = list_insert_nth(segdbDesc->segment_database_info->freelist,
lastWriterPos + 1, segdbDesc);
else
segdbDesc->segment_database_info->freelist =
lcons(segdbDesc, segdbDesc->segment_database_info->freelist);
}
INCR_COUNT(cdbinfo, numIdleQEs);
MemoryContextSwitchTo(oldContext);
return;
destroy_segdb:
cdbconn_termSegmentDescriptor(segdbDesc);
if (isWriter)
{
markCurrentGxactWriterGangLost();
}
MemoryContextSwitchTo(oldContext);
}
static int
nextQEIdentifer(CdbComponentDatabases *cdbs)
{
int result;
if (!cdbs->freeCounterList)
return cdbs->qeCounter++;
result = linitial_int(cdbs->freeCounterList);
cdbs->freeCounterList = list_delete_first(cdbs->freeCounterList);
return result;
}
bool
cdbcomponent_qesExist(void)
{
return !cdb_component_dbs ? false :
(cdb_component_dbs->numIdleQEs > 0 || cdb_component_dbs->numActiveQEs > 0);
}
bool
cdbcomponent_activeQEsExist(void)
{
return !cdb_component_dbs ? false : cdb_component_dbs->numActiveQEs > 0;
}
/*
* Find CdbComponentDatabaseInfo in the array by segment index.
*/
CdbComponentDatabaseInfo *
cdbcomponent_getComponentInfo(int contentId)
{
CdbComponentDatabaseInfo *cdbInfo = NULL;
CdbComponentDatabases *cdbs;
cdbs = cdbcomponent_getCdbComponents();
if (contentId < -1 || contentId >= cdbs->total_segments)