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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
|
/*-------------------------------------------------------------------------
*
* pgxcnode.c
* Functions for communication with nodes through pooled connections.
*
* This is mostly a backend-side counterpart to the pool manager. Each
* session acquires connections to remote nodes, and uses them to execute
* queries.
*
* Currently, we only allow a single connection to each remote node. If
* a query includes multiple nodes that communicate with a given remote
* node (e.g. Append with multiple RemoteSubquery children), then the
* connection may need to be buffered (see BufferConnection).
*
* Following is an overview of the basic methods for node management and
* communication over the handles.
*
*
* node handle management
* ----------------------
* get_any_handle - acquire handle for replicated table
* get_handles - acquire handles to all specified nodes
* get_current_handles - return already acquired handles
* release_handles - release all connection (back to pool)
*
*
* node handle management
* ----------------------
* PGXCNodeGetNodeOid - OID for node by index in handle array
* PGXCNodeGetNodeIdFromName - determine index in handle array by name
* PGXCNodeGetNodeId - determine index in handle array from OID
*
*
* session/transaction parameters
* ------------------------------
* PGXCNodeSetParam - add new parameter
* PGXCNodeResetParams - reset (local or session) parameters
* PGXCNodeGetTransactionParamStr - generate SET with transaction params
* PGXCNodeGetSessionParamStr - generate SET with session params
*
*
* low-level TCP buffer access
* ---------------------------
* pgxc_node_receive - receive data into input buffers for connections
* pgxc_node_read_data - read data for one particular connection
* get_message - read one complete message from a handle
* send_some - send a chunk of data to remote node
*
*
* send higher-level messages to remote node
* -----------------------------------------
* pgxc_node_send_parse - sends PARSE (part of extended protocol)
* pgxc_node_send_bind - sends BIND (part of extended protocol)
* pgxc_node_send_describe - sends DESCRIBE (part of extended protocol)
* pgxc_node_send_execute - sends EXECUTE (part of extended protocol)
* pgxc_node_send_flush - sends FLUSH (part of extended protocol)
* pgxc_node_send_close - sends close (C)
* pgxc_node_send_sync - sends sync (S)
* pgxc_node_send_query - simple query protocol (Q)
* pgxc_node_send_rollback - simple query on failed connection (Q)
* pgxc_node_send_query_extended - extended query protocol (PARSE, ...)
*
*
* XL-specific messages to remote nodes
* ------------------------------------
* pgxc_node_send_plan - sends plan to remote node (p)
* pgxc_node_send_gxid - sends GXID to remote node (g)
* pgxc_node_send_cmd_id - sends CommandId to remote node (M)
* pgxc_node_send_snapshot - sends snapshot to remote node (s)
* pgxc_node_send_timestamp - sends timestamp to remote node (t)
*
*
* misc functions
* --------------
* pgxc_node_set_query - send SET by simple protocol, wait for "ready"
* pgxc_node_flush - flush all data from the output buffer
*
*
* XXX We should add the custom messages (gxid, snapshot, ...) to the SGML
* documentation describing message formats.
*
* XXX What about using simple list, instead of the arrays? Or define new
* structure grouping all the important parameters (buffer, size, maxsize).
*
* XXX The comments claim that dn_handles and co_handles are allocated in
* Transaction context, but in fact those are allocated in TopMemoryContext.
* Otherwise we wouldn't be able to use persistent connections, which keeps
* connections for the whole session.
*
* XXX The comment at pgxc_node_free mentions TopTransactionContext, so
* perhaps we should consider using that?
*
*
* Portions Copyright (c) 2012-2014, TransLattice, Inc.
* Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
* Portions Copyright (c) 2010-2012 Postgres-XC Development Group
*
* IDENTIFICATION
* src/backend/pgxc/pool/pgxcnode.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <poll.h>
#ifdef __sun
#include <sys/filio.h>
#endif
#include <sys/time.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include "access/gtm.h"
#include "access/transam.h"
#include "access/xact.h"
#include "access/htup_details.h"
#include "catalog/pg_type.h"
#include "catalog/pg_collation.h"
#include "catalog/pgxc_node.h"
#include "commands/prepare.h"
#include "gtm/gtm_c.h"
#include "miscadmin.h"
#include "nodes/nodes.h"
#include "pgxc/execRemote.h"
#include "pgxc/locator.h"
#include "pgxc/nodemgr.h"
#include "pgxc/pause.h"
#include "pgxc/pgxc.h"
#include "pgxc/pgxcnode.h"
#include "pgxc/poolmgr.h"
#include "storage/ipc.h"
#include "storage/lwlock.h"
#include "tcop/dest.h"
#include "utils/builtins.h"
#include "utils/elog.h"
#include "utils/memutils.h"
#include "utils/fmgroids.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/lsyscache.h"
#include "utils/formatting.h"
#include "utils/snapmgr.h"
#include "utils/tqual.h"
#include "../interfaces/libpq/libpq-fe.h"
#define CMD_ID_MSG_LEN 8
/* Number of connections held */
static int datanode_count = 0;
static int coord_count = 0;
/*
* Datanode and coordinator handles (sockets obtained from the pooler),
* initialized in the TopMemoryContext memory context. Those connections
* are used during query execution to communicate wit the nodes.
*
* XXX At this point we have only a single connection to each node, and
* use multiplex it for multiple cursors (see BufferConnection).
*/
static PGXCNodeHandle *dn_handles = NULL; /* datanodes */
static PGXCNodeHandle *co_handles = NULL; /* coordinators */
/* Current number of datanode and coordinator handles. */
int NumDataNodes;
int NumCoords;
volatile bool HandlesInvalidatePending = false;
volatile bool HandlesRefreshPending = false;
/*
* Session/transaction parameters that need to to be set on new connections.
*/
static List *session_param_list = NIL;
static List *local_param_list = NIL;
static StringInfo session_params;
static StringInfo local_params;
typedef struct
{
NameData name;
NameData value;
int flags;
} ParamEntry;
static bool DoInvalidateRemoteHandles(void);
static bool DoRefreshRemoteHandles(void);
static void pgxc_node_init(PGXCNodeHandle *handle, int sock,
bool global_session, int pid);
static void pgxc_node_free(PGXCNodeHandle *handle);
static void pgxc_node_all_free(void);
static int get_int(PGXCNodeHandle * conn, size_t len, int *out);
static int get_char(PGXCNodeHandle * conn, char *out);
/*
* Initialize empty PGXCNodeHandle struct
*/
static void
init_pgxc_handle(PGXCNodeHandle *pgxc_handle)
{
/*
* Socket descriptor is small non-negative integer,
* Indicate the handle is not initialized yet
*/
pgxc_handle->sock = NO_SOCKET;
/* Initialise buffers */
pgxc_handle->error = NULL;
pgxc_handle->outSize = 16 * 1024;
pgxc_handle->outBuffer = (char *) palloc(pgxc_handle->outSize);
pgxc_handle->inSize = 16 * 1024;
pgxc_handle->inBuffer = (char *) palloc(pgxc_handle->inSize);
pgxc_handle->combiner = NULL;
pgxc_handle->inStart = 0;
pgxc_handle->inEnd = 0;
pgxc_handle->inCursor = 0;
pgxc_handle->outEnd = 0;
pgxc_handle->needSync = false;
if (pgxc_handle->outBuffer == NULL || pgxc_handle->inBuffer == NULL)
{
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory")));
}
}
/*
* InitMultinodeExecutor
* Initialize datanode and coordinator handles.
*
* Acquires list of nodes from the node manager, and initializes handle
* for each one.
*
* Also determines PGXCNodeId to index in the proper array of handles
* (co_handles or dn_handles), depending on the type of this node.
*/
void
InitMultinodeExecutor(bool is_force)
{
int count;
Oid *coOids, *dnOids;
MemoryContext oldcontext;
/* Free all the existing information first */
if (is_force)
pgxc_node_all_free();
/* This function could get called multiple times because of sigjmp */
if (dn_handles != NULL &&
co_handles != NULL)
return;
/* Update node table in the shared memory */
PgxcNodeListAndCount();
/* Get classified list of node Oids */
PgxcNodeGetOids(&coOids, &dnOids, &NumCoords, &NumDataNodes, true);
/*
* Coordinator and datanode handles should be available during all the
* session lifetime
*/
oldcontext = MemoryContextSwitchTo(TopMemoryContext);
/* Do proper initialization of handles */
if (NumDataNodes > 0)
dn_handles = (PGXCNodeHandle *)
palloc(NumDataNodes * sizeof(PGXCNodeHandle));
if (NumCoords > 0)
co_handles = (PGXCNodeHandle *)
palloc(NumCoords * sizeof(PGXCNodeHandle));
if ((!dn_handles && NumDataNodes > 0) ||
(!co_handles && NumCoords > 0))
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory for node handles")));
/* Initialize new empty slots */
for (count = 0; count < NumDataNodes; count++)
{
init_pgxc_handle(&dn_handles[count]);
dn_handles[count].nodeoid = dnOids[count];
dn_handles[count].nodeid = get_pgxc_node_id(dnOids[count]);
strncpy(dn_handles[count].nodename, get_pgxc_nodename(dnOids[count]),
NAMEDATALEN);
strncpy(dn_handles[count].nodehost, get_pgxc_nodehost(dnOids[count]),
NAMEDATALEN);
dn_handles[count].nodeport = get_pgxc_nodeport(dnOids[count]);
}
for (count = 0; count < NumCoords; count++)
{
init_pgxc_handle(&co_handles[count]);
co_handles[count].nodeoid = coOids[count];
co_handles[count].nodeid = get_pgxc_node_id(coOids[count]);
strncpy(co_handles[count].nodename, get_pgxc_nodename(coOids[count]),
NAMEDATALEN);
strncpy(co_handles[count].nodehost, get_pgxc_nodehost(coOids[count]),
NAMEDATALEN);
co_handles[count].nodeport = get_pgxc_nodeport(coOids[count]);
}
datanode_count = 0;
coord_count = 0;
PGXCNodeId = 0;
MemoryContextSwitchTo(oldcontext);
/*
* Determine index of a handle representing this node, either in the
* coordinator or datanode handles, depending on the type of this
* node. The index gets stored in PGXCNodeId.
*
* XXX It's a bit confusing that this may point either to co_handles
* or dn_handles, and may easily lead to bugs when used with the
* incorrect array.
*/
if (IS_PGXC_COORDINATOR)
{
for (count = 0; count < NumCoords; count++)
{
if (pg_strcasecmp(PGXCNodeName,
get_pgxc_nodename(co_handles[count].nodeoid)) == 0)
PGXCNodeId = count + 1;
}
}
else /* DataNode */
{
for (count = 0; count < NumDataNodes; count++)
{
if (pg_strcasecmp(PGXCNodeName,
get_pgxc_nodename(dn_handles[count].nodeoid)) == 0)
PGXCNodeId = count + 1;
}
}
}
/*
* pgxc_node_free
* Close the socket handle (local copy) and free occupied memory.
*
* Note that this only closes the socket, but we do not free the handle
* and its members. This will be taken care of when the transaction ends,
* when TopTransactionContext is destroyed in xact.c.
*/
static void
pgxc_node_free(PGXCNodeHandle *handle)
{
if (handle->sock != NO_SOCKET)
close(handle->sock);
handle->sock = NO_SOCKET;
}
/*
* pgxc_node_all_free
* Free all the node handles cached in TopMemoryContext.
*/
static void
pgxc_node_all_free(void)
{
int i, j;
for (i = 0; i < 2; i++)
{
int num_nodes = 0;
PGXCNodeHandle *array_handles;
switch (i)
{
case 0:
num_nodes = NumCoords;
array_handles = co_handles;
break;
case 1:
num_nodes = NumDataNodes;
array_handles = dn_handles;
break;
default:
Assert(0);
}
for (j = 0; j < num_nodes; j++)
{
PGXCNodeHandle *handle = &array_handles[j];
pgxc_node_free(handle);
}
if (array_handles)
pfree(array_handles);
}
co_handles = NULL;
dn_handles = NULL;
HandlesInvalidatePending = false;
HandlesRefreshPending = false;
}
/*
* pgxc_node_init
* Initialize the handle to communicate to node throught the socket.
*
* Stored PID of the remote backend, and of requested, sends the global
* session string to the remote node.
*/
static void
pgxc_node_init(PGXCNodeHandle *handle, int sock, bool global_session, int pid)
{
char *init_str;
handle->sock = sock;
handle->backend_pid = pid;
handle->transaction_status = 'I';
PGXCNodeSetConnectionState(handle, DN_CONNECTION_STATE_IDLE);
handle->read_only = true;
handle->ck_resp_rollback = false;
handle->combiner = NULL;
#ifdef DN_CONNECTION_DEBUG
handle->have_row_desc = false;
#endif
handle->error = NULL;
handle->outEnd = 0;
handle->inStart = 0;
handle->inEnd = 0;
handle->inCursor = 0;
handle->needSync = false;
/*
* We got a new connection, set on the remote node the session parameters
* if defined. The transaction parameter should be sent after BEGIN.
*/
if (global_session)
{
init_str = PGXCNodeGetSessionParamStr();
if (init_str)
{
pgxc_node_set_query(handle, init_str);
}
}
}
/*
* pgxc_node_receive
* Wait while at least one of the connections has data available, and
* read the data into the buffer.
*/
bool
pgxc_node_receive(const int conn_count,
PGXCNodeHandle ** connections, struct timeval * timeout)
{
#define ERROR_OCCURED true
#define NO_ERROR_OCCURED false
int i,
sockets_to_poll,
poll_val;
bool is_msg_buffered;
long timeout_ms;
struct pollfd pool_fd[conn_count];
/* sockets to be polled index */
sockets_to_poll = 0;
is_msg_buffered = false;
for (i = 0; i < conn_count; i++)
{
/* If connection has a buffered message */
if (HAS_MESSAGE_BUFFERED(connections[i]))
{
is_msg_buffered = true;
break;
}
}
for (i = 0; i < conn_count; i++)
{
/* If connection finished sending do not wait input from it */
if (connections[i]->state == DN_CONNECTION_STATE_IDLE || HAS_MESSAGE_BUFFERED(connections[i]))
{
pool_fd[i].fd = -1;
pool_fd[i].events = 0;
continue;
}
/* prepare select params */
if (connections[i]->sock > 0)
{
pool_fd[i].fd = connections[i]->sock;
pool_fd[i].events = POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND;
sockets_to_poll++;
}
else
{
/* flag as bad, it will be removed from the list */
PGXCNodeSetConnectionState(connections[i],
DN_CONNECTION_STATE_ERROR_FATAL);
pool_fd[i].fd = -1;
pool_fd[i].events = 0;
}
}
/*
* Return if we do not have connections to receive input
*/
if (sockets_to_poll == 0)
{
if (is_msg_buffered)
return NO_ERROR_OCCURED;
return ERROR_OCCURED;
}
/* do conversion from the select behaviour */
if ( timeout == NULL )
timeout_ms = -1;
else
timeout_ms = (timeout->tv_sec * (uint64_t) 1000) + (timeout->tv_usec / 1000);
retry:
CHECK_FOR_INTERRUPTS();
poll_val = poll(pool_fd, conn_count, timeout_ms);
if (poll_val < 0)
{
/* error - retry if EINTR */
if (errno == EINTR || errno == EAGAIN)
goto retry;
elog(WARNING, "poll() error: %d", errno);
if (errno)
return ERROR_OCCURED;
return NO_ERROR_OCCURED;
}
if (poll_val == 0)
{
/* Handle timeout */
elog(DEBUG1, "timeout %ld while waiting for any response from %d connections", timeout_ms,conn_count);
for (i = 0; i < conn_count; i++)
PGXCNodeSetConnectionState(connections[i],
DN_CONNECTION_STATE_ERROR_FATAL);
return NO_ERROR_OCCURED;
}
/* read data */
for (i = 0; i < conn_count; i++)
{
PGXCNodeHandle *conn = connections[i];
if( pool_fd[i].fd == -1 )
continue;
if ( pool_fd[i].fd == conn->sock )
{
if( pool_fd[i].revents & POLLIN )
{
int read_status = pgxc_node_read_data(conn, true);
if ( read_status == EOF || read_status < 0 )
{
/* Can not read - no more actions, just discard connection */
PGXCNodeSetConnectionState(conn,
DN_CONNECTION_STATE_ERROR_FATAL);
add_error_message(conn, "unexpected EOF on datanode connection.");
elog(WARNING, "unexpected EOF on datanode oid connection: %d", conn->nodeoid);
/*
* before returning, also update the shared health
* status field to indicate that this node could be
* possibly unavailable.
*
* Note that this error could be due to a stale handle
* and it's possible that another backend might have
* already updated the health status OR the node
* might have already come back since the last disruption
*/
PoolPingNodeRecheck(conn->nodeoid);
/* Should we read from the other connections before returning? */
return ERROR_OCCURED;
}
}
else if (
(pool_fd[i].revents & POLLERR) ||
(pool_fd[i].revents & POLLHUP) ||
(pool_fd[i].revents & POLLNVAL)
)
{
PGXCNodeSetConnectionState(connections[i],
DN_CONNECTION_STATE_ERROR_FATAL);
add_error_message(conn, "unexpected network error on datanode connection");
elog(WARNING, "unexpected EOF on datanode oid connection: %d with event %d", conn->nodeoid,pool_fd[i].revents);
/* Should we check/read from the other connections before returning? */
return ERROR_OCCURED;
}
}
}
return NO_ERROR_OCCURED;
}
/*
* pgxc_node_read_data
* Read incoming data from the node TCP connection.
*/
int
pgxc_node_read_data(PGXCNodeHandle *conn, bool close_if_error)
{
int someread = 0;
int nread;
if (conn->sock < 0)
{
if (close_if_error)
add_error_message(conn, "bad socket");
return EOF;
}
/* Left-justify any data in the buffer to make room */
if (conn->inStart < conn->inEnd)
{
if (conn->inStart > 0)
{
memmove(conn->inBuffer, conn->inBuffer + conn->inStart,
conn->inEnd - conn->inStart);
conn->inEnd -= conn->inStart;
conn->inCursor -= conn->inStart;
conn->inStart = 0;
}
}
else
{
/* buffer is logically empty, reset it */
conn->inStart = conn->inCursor = conn->inEnd = 0;
}
/*
* If the buffer is fairly full, enlarge it. We need to be able to enlarge
* the buffer in case a single message exceeds the initial buffer size. We
* enlarge before filling the buffer entirely so as to avoid asking the
* kernel for a partial packet. The magic constant here should be large
* enough for a TCP packet or Unix pipe bufferload. 8K is the usual pipe
* buffer size, so...
*/
if (conn->inSize - conn->inEnd < 8192)
{
if (ensure_in_buffer_capacity(conn->inEnd + (size_t) 8192, conn) != 0)
{
/*
* We don't insist that the enlarge worked, but we need some room
*/
if (conn->inSize - conn->inEnd < 100)
{
if (close_if_error)
add_error_message(conn, "can not allocate buffer");
return -1;
}
}
}
retry:
nread = recv(conn->sock, conn->inBuffer + conn->inEnd,
conn->inSize - conn->inEnd, 0);
if (nread < 0)
{
if (errno == EINTR)
goto retry;
/* Some systems return EAGAIN/EWOULDBLOCK for no data */
#ifdef EAGAIN
if (errno == EAGAIN)
return someread;
#endif
#if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
if (errno == EWOULDBLOCK)
return someread;
#endif
/* We might get ECONNRESET here if using TCP and backend died */
#ifdef ECONNRESET
if (errno == ECONNRESET)
{
/*
* OK, we are getting a zero read even though select() says ready. This
* means the connection has been closed. Cope.
*/
if (close_if_error)
{
add_error_message(conn,
"Datanode closed the connection unexpectedly\n"
"\tThis probably means the Datanode terminated abnormally\n"
"\tbefore or while processing the request.\n");
PGXCNodeSetConnectionState(conn,
DN_CONNECTION_STATE_ERROR_FATAL); /* No more connection to
* backend */
closesocket(conn->sock);
conn->sock = NO_SOCKET;
}
return -1;
}
#endif
if (close_if_error)
add_error_message(conn, "could not receive data from server");
return -1;
}
if (nread > 0)
{
conn->inEnd += nread;
/*
* Hack to deal with the fact that some kernels will only give us back
* 1 packet per recv() call, even if we asked for more and there is
* more available. If it looks like we are reading a long message,
* loop back to recv() again immediately, until we run out of data or
* buffer space. Without this, the block-and-restart behavior of
* libpq's higher levels leads to O(N^2) performance on long messages.
*
* Since we left-justified the data above, conn->inEnd gives the
* amount of data already read in the current message. We consider
* the message "long" once we have acquired 32k ...
*/
if (conn->inEnd > 32768 &&
(conn->inSize - conn->inEnd) >= 8192)
{
someread = 1;
goto retry;
}
return 1;
}
if (nread == 0)
{
if (close_if_error)
elog(DEBUG1, "nread returned 0");
return EOF;
}
if (someread)
return 1; /* got a zero read after successful tries */
return 0;
}
/*
* Get one character from the connection buffer and advance cursor.
*
* Returns 0 if enough data is available in the buffer (and the value is
* returned in the 'out' parameter). Otherwise the function returns EOF.
*/
static int
get_char(PGXCNodeHandle * conn, char *out)
{
if (conn->inCursor < conn->inEnd)
{
*out = conn->inBuffer[conn->inCursor++];
return 0;
}
return EOF;
}
/*
* Try reading an integer from the connection buffer and advance cursor.
*
* Returns 0 if enough data is available in the buffer (and the value is
* returned in the 'out' parameter). Otherwise the function returns EOF.
*
* XXX We only ever call this once with len=4, so simplify the function.
*/
static int
get_int(PGXCNodeHandle *conn, size_t len, int *out)
{
unsigned short tmp2;
unsigned int tmp4;
/*
* XXX This seems somewhat inconsistent with get_char(). Perhaps this
* should use >= to behave in the same way?
*/
if (conn->inCursor + len > conn->inEnd)
return EOF;
switch (len)
{
case 2:
memcpy(&tmp2, conn->inBuffer + conn->inCursor, 2);
conn->inCursor += 2;
*out = (int) ntohs(tmp2);
break;
case 4:
memcpy(&tmp4, conn->inBuffer + conn->inCursor, 4);
conn->inCursor += 4;
*out = (int) ntohl(tmp4);
break;
default:
add_error_message(conn, "not supported int size");
return EOF;
}
return 0;
}
/*
* get_message
* Attempt to read the whole message from the input buffer, if possible.
*
* If the entire message is in the input buffer of the connection, reads it
* into a buffer (len and msg parameters) and returns the message type.
*
* If the input buffer does not contain the whole message, the cursor is
* left unchanged, the connection status is se to DN_CONNECTION_STATE_QUERY
* indicating it needs to receive more data, and \0 is returned (instead of
* an actual message type).
*
* conn - connection to read from
* len - returned length of the data where msg is pointing to
* msg - returns pointer to position in the incoming buffer
*
* The buffer probably will be overwritten upon next receive, so if caller
* wants to refer it later it should make a copy.
*/
char
get_message(PGXCNodeHandle *conn, int *len, char **msg)
{
char msgtype;
/*
* Try reading the first char (message type) and integer (message length).
*
* Both functions return 0 (false) in case of success, and EOF (true) in
* case of failure. So we call get_char() first, and only if it succeeds
* the get_int() gets called.
*/
if (get_char(conn, &msgtype) || get_int(conn, 4, len))
{
/* Successful get_char/get_int would move cursor, restore position. */
conn->inCursor = conn->inStart;
return '\0';
}
/* The message length includes the length header too, so subtract it. */
*len -= 4;
/*
* If the whole message is not in the buffer, we need to read more data.
*
* Reading function will discard already consumed data in the buffer till
* conn->inCursor. To avoid extra/handle cycles we need to fit the whole
* message (and not just a part of it) into the buffer. So let's ensure
* the buffer is large enough.
*
* We need 1 byte for for message type, 4 bytes for message length and
* the message itself (the length is currently in *len). The buffer may
* already be large enough, in which case ensure_in_buffer_capacity()
* will return immediately .
*/
if (conn->inCursor + *len > conn->inEnd)
{
/* ensure space for the whole message (including 5B header)
*
* FIXME Add check of the return value. Non-zero value means failure.
*/
ensure_in_buffer_capacity(5 + (size_t) *len, conn);
conn->inCursor = conn->inStart;
return '\0';
}
/* Great, the whole message in the buffer. */
*msg = conn->inBuffer + conn->inCursor;
conn->inCursor += *len;
conn->inStart = conn->inCursor;
return msgtype;
}
/*
* release_handles
* Release all node connections back to pool and free the memory.
*/
void
release_handles(void)
{
bool destroy = false;
int i;
if (HandlesInvalidatePending)
{
DoInvalidateRemoteHandles();
return;
}
/* don't free connection if holding a cluster lock */
if (cluster_ex_lock_held)
return;
/* quick exit if we have no connections to release */
if (datanode_count == 0 && coord_count == 0)
return;
/* Do not release connections if we have prepared statements on nodes */
if (HaveActiveDatanodeStatements())
return;
/* Free Datanodes handles */
for (i = 0; i < NumDataNodes; i++)
{
PGXCNodeHandle *handle = &dn_handles[i];
if (handle->sock != NO_SOCKET)
{
/*
* Connections at this point should be completely inactive,
* otherwise abaandon them. We can not allow not cleaned up
* connection is returned to pool.
*/
if (handle->state != DN_CONNECTION_STATE_IDLE ||
handle->transaction_status != 'I')
{
destroy = true;
elog(DEBUG1, "Connection to Datanode %d has unexpected state %d and will be dropped",
handle->nodeoid, handle->state);
}
pgxc_node_free(handle);
}
}
/*
* XXX Not sure why we coordinator connections are only released when on
* a coordinator. Perhaps we never acquire connections to coordinators on
* datanodes? Seems like a rather minor optimization anyway.
*/
if (IS_PGXC_COORDINATOR)
{
/* Free Coordinator handles */
for (i = 0; i < NumCoords; i++)
{
PGXCNodeHandle *handle = &co_handles[i];
if (handle->sock != NO_SOCKET)
{
/*
* Connections at this point should be completely inactive,
* otherwise abaandon them. We can not allow not cleaned up
* connection is returned to pool.
*/
if (handle->state != DN_CONNECTION_STATE_IDLE ||
handle->transaction_status != 'I')
{
destroy = true;
elog(DEBUG1, "Connection to Coordinator %d has unexpected state %d and will be dropped",
handle->nodeoid, handle->state);
}
pgxc_node_free(handle);
}
}
}
/*
* And finally release all the connections held by this backend back
* to the connection pool.
*/
PoolManagerReleaseConnections(destroy);
datanode_count = 0;
coord_count = 0;
}
/*
* ensure_buffer_capacity
* Ensure that the supplied buffer has at least the required capacity.
*
* currbuf - the currently allocated buffer
* currsize - size of the current buffer (in bytes)
* bytes_needed - required capacity (in bytes)
*
* We shall return the new buffer, if allocated successfully and set newsize_p
* to contain the size of the repalloc-ed buffer.
*
* If allocation fails, NULL is returned.
*
* The function checks for requests beyond MaxAllocSize and throws an error
* if the request exceeds the limit.
*/
static char *
ensure_buffer_capacity(char *currbuf, size_t currsize, size_t bytes_needed, size_t *newsize_p)
{
char *newbuf;
Size newsize = (Size) currsize;
/* XXX Perhaps use AllocSizeIsValid instead? */
if (((Size) bytes_needed) >= MaxAllocSize)
ereport(ERROR,
(ENOSPC,
errmsg("out of memory"),
errdetail("Cannot enlarge buffer containing %ld bytes by %ld more bytes.",
currsize, bytes_needed)));
/* if the buffer is already large enough, we're done */
if (bytes_needed <= newsize)
{
*newsize_p = currsize;
return currbuf;
}
/*
* The current size of the buffer should never be zero (init_pgxc_handle
* guarantees that.
*/
Assert(newsize > 0);
/*
* Double the buffer size until we have enough space to hold bytes_needed
*/
while (bytes_needed > newsize)
newsize = 2 * newsize;
/*
* Clamp to MaxAllocSize in case we went past it. Note we are assuming
* here that MaxAllocSize <= INT_MAX/2, else the above loop could
* overflow. We will still have newsize >= bytes_needed.
*/
if (newsize > (int) MaxAllocSize)
newsize = (int) MaxAllocSize;
newbuf = repalloc(currbuf, newsize);
if (newbuf)
{
/* repalloc succeeded, set new size and return the buffer */
*newsize_p = newsize;
return newbuf;
}
/*
* If we fail to double the buffer, try to repalloc a buffer of the given
* size, rounded to the next multiple of 8192 and see if that works.
*/
newsize = bytes_needed;
newsize = ((bytes_needed / 8192) + 1) * 8192;
newbuf = repalloc(currbuf, newsize);
if (newbuf)
{
/* repalloc succeeded, set new size and return the buffer */
*newsize_p = newsize;
return newbuf;
}
/* repalloc failed */
return NULL;
}
/*
* ensure_in_buffer_capacity
* Ensure specified amount of data can fit to the input buffer of a handle.
*
* Returns 0 in case of success, EOF otherwise.
*/
int
ensure_in_buffer_capacity(size_t bytes_needed, PGXCNodeHandle *handle)
{
size_t newsize;
char *newbuf = ensure_buffer_capacity(handle->inBuffer, handle->inSize,
bytes_needed, &newsize);
if (newbuf)
{
handle->inBuffer = newbuf;
handle->inSize = newsize;
return 0;
}
return EOF;
}
/*
* ensure_out_buffer_capacity
* Ensure specified amount of data can fit to the output buffer of a handle.
*
* Returns 0 in case of success, EOF otherwise.
*/
int
ensure_out_buffer_capacity(size_t bytes_needed, PGXCNodeHandle *handle)
{
size_t newsize;
char *newbuf = ensure_buffer_capacity(handle->outBuffer, handle->outSize,
bytes_needed, &newsize);
if (newbuf)
{
handle->outBuffer = newbuf;
handle->outSize = newsize;
return 0;
}
return EOF;
}
/*
* send_some
* Send specified amount of data from the output buffer over the handle.
*/
int
send_some(PGXCNodeHandle *handle, int len)
{
char *ptr = handle->outBuffer;
int remaining = handle->outEnd;
int result = 0;
/* while there's still data to send */
while (len > 0)
{
int sent;
#ifndef WIN32
sent = send(handle->sock, ptr, len, 0);
#else
/*
* Windows can fail on large sends, per KB article Q201213. The failure-point
* appears to be different in different versions of Windows, but 64k should
* always be safe.
*/
sent = send(handle->sock, ptr, Min(len, 65536), 0);
#endif
if (sent < 0)
{
/*
* Anything except EAGAIN/EWOULDBLOCK/EINTR is trouble. If it's
* EPIPE or ECONNRESET, assume we've lost the backend connection
* permanently.
*/
switch (errno)
{
#ifdef EAGAIN
case EAGAIN:
break;
#endif
#if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
case EWOULDBLOCK:
break;
#endif
case EINTR:
continue;
case EPIPE:
#ifdef ECONNRESET
case ECONNRESET:
#endif
add_error_message(handle, "server closed the connection unexpectedly\n"
"\tThis probably means the server terminated abnormally\n"
"\tbefore or while processing the request.\n");
/*
* We used to close the socket here, but that's a bad idea
* since there might be unread data waiting (typically, a
* NOTICE message from the backend telling us it's
* committing hara-kiri...). Leave the socket open until
* pqReadData finds no more data can be read. But abandon
* attempt to send data.
*/
handle->outEnd = 0;
return -1;
default:
add_error_message(handle, "could not send data to server");
/* We don't assume it's a fatal error... */
handle->outEnd = 0;
return -1;
}
}
else
{
ptr += sent;
len -= sent;
remaining -= sent;
}
if (len > 0)
{
struct pollfd pool_fd;
int poll_ret;
/*
* Wait for the socket to become ready again to receive more data.
* For some cases, especially while writing large sums of data
* during COPY protocol and when the remote node is not capable of
* handling data at the same speed, we might otherwise go in a
* useless tight loop, consuming all available local resources
*
* Use a small timeout of 1s to avoid infinite wait
*/
pool_fd.fd = handle->sock;
pool_fd.events = POLLOUT;
poll_ret = poll(&pool_fd, 1, 1000);
if (poll_ret < 0)
{
if (errno == EAGAIN || errno == EINTR)
continue;
else
{
add_error_message(handle, "poll failed ");
handle->outEnd = 0;
return -1;
}
}
else if (poll_ret == 1)
{
if (pool_fd.revents & POLLHUP)
{
add_error_message(handle, "remote end disconnected");
handle->outEnd = 0;
return -1;
}
}
}
}
/* shift the remaining contents of the buffer */
if (remaining > 0)
memmove(handle->outBuffer, ptr, remaining);
handle->outEnd = remaining;
return result;
}
/*
* pgxc_node_send_parse
* Send PARSE message with specified statement down to the datanode.
*/
int
pgxc_node_send_parse(PGXCNodeHandle * handle, const char* statement,
const char *query, short num_params, Oid *param_types)
{
/* statement name size (allow NULL) */
int stmtLen = statement ? strlen(statement) + 1 : 1;
/* size of query string */
int strLen = strlen(query) + 1;
char **paramTypes = (char **)palloc(sizeof(char *) * num_params);
/* total size of parameter type names */
int paramTypeLen;
/* message length */
int msgLen;
int cnt_params;
#ifdef USE_ASSERT_CHECKING
size_t old_outEnd = handle->outEnd;
#endif
/* if there are parameters, param_types should exist */
Assert(num_params <= 0 || param_types);
/* 2 bytes for number of parameters, preceding the type names */
paramTypeLen = 2;
/* find names of the types of parameters */
for (cnt_params = 0; cnt_params < num_params; cnt_params++)
{
Oid typeoid;
/* Parameters with no types are simply ignored */
if (OidIsValid(param_types[cnt_params]))
typeoid = param_types[cnt_params];
else
typeoid = INT4OID;
paramTypes[cnt_params] = format_type_be(typeoid);
paramTypeLen += strlen(paramTypes[cnt_params]) + 1;
}
/* size + stmtLen + strlen + paramTypeLen */
msgLen = 4 + stmtLen + strLen + paramTypeLen;
/* msgType + msgLen */
if (ensure_out_buffer_capacity(handle->outEnd + 1 + msgLen, handle) != 0)
{
add_error_message(handle, "out of memory");
return EOF;
}
handle->outBuffer[handle->outEnd++] = 'P';
/* size */
msgLen = htonl(msgLen);
memcpy(handle->outBuffer + handle->outEnd, &msgLen, 4);
handle->outEnd += 4;
/* statement name */
if (statement)
{
memcpy(handle->outBuffer + handle->outEnd, statement, stmtLen);
handle->outEnd += stmtLen;
}
else
handle->outBuffer[handle->outEnd++] = '\0';
/* query */
memcpy(handle->outBuffer + handle->outEnd, query, strLen);
handle->outEnd += strLen;
/* parameter types */
Assert(sizeof(num_params) == 2);
*((short *)(handle->outBuffer + handle->outEnd)) = htons(num_params);
handle->outEnd += sizeof(num_params);
/*
* instead of parameter ids we should send parameter names (qualified by
* schema name if required). The OIDs of types can be different on
* Datanodes.
*/
for (cnt_params = 0; cnt_params < num_params; cnt_params++)
{
memcpy(handle->outBuffer + handle->outEnd, paramTypes[cnt_params],
strlen(paramTypes[cnt_params]) + 1);
handle->outEnd += strlen(paramTypes[cnt_params]) + 1;
pfree(paramTypes[cnt_params]);
}
pfree(paramTypes);
Assert(old_outEnd + ntohl(msgLen) + 1 == handle->outEnd);
return 0;
}
/*
* pgxc_node_send_plan
* Send PLAN message down to the datanode.
*/
int
pgxc_node_send_plan(PGXCNodeHandle * handle, const char *statement,
const char *query, const char *planstr,
short num_params, Oid *param_types)
{
int stmtLen;
int queryLen;
int planLen;
int paramTypeLen;
int msgLen;
char **paramTypes = (char **)palloc(sizeof(char *) * num_params);
int i;
short tmp_num_params;
/* Invalid connection state, return error */
if (handle->state != DN_CONNECTION_STATE_IDLE)
return EOF;
/* statement name size (do not allow NULL) */
stmtLen = strlen(statement) + 1;
/* source query size (do not allow NULL) */
queryLen = strlen(query) + 1;
/* query plan size (do not allow NULL) */
planLen = strlen(planstr) + 1;
/* 2 bytes for number of parameters, preceding the type names */
paramTypeLen = 2;
/* find names of the types of parameters */
for (i = 0; i < num_params; i++)
{
paramTypes[i] = format_type_be(param_types[i]);
paramTypeLen += strlen(paramTypes[i]) + 1;
}
/* size + pnameLen + queryLen + parameters */
msgLen = 4 + queryLen + stmtLen + planLen + paramTypeLen;
/* msgType + msgLen */
if (ensure_out_buffer_capacity(handle->outEnd + 1 + msgLen, handle) != 0)
{
add_error_message(handle, "out of memory");
return EOF;
}
handle->outBuffer[handle->outEnd++] = 'p';
/* size */
msgLen = htonl(msgLen);
memcpy(handle->outBuffer + handle->outEnd, &msgLen, 4);
handle->outEnd += 4;
/* statement name */
memcpy(handle->outBuffer + handle->outEnd, statement, stmtLen);
handle->outEnd += stmtLen;
/* source query */
memcpy(handle->outBuffer + handle->outEnd, query, queryLen);
handle->outEnd += queryLen;
/* query plan */
memcpy(handle->outBuffer + handle->outEnd, planstr, planLen);
handle->outEnd += planLen;
/* parameter types */
tmp_num_params = htons(num_params);
memcpy(handle->outBuffer + handle->outEnd, &tmp_num_params, sizeof(tmp_num_params));
handle->outEnd += sizeof(tmp_num_params);
/*
* instead of parameter ids we should send parameter names (qualified by
* schema name if required). The OIDs of types can be different on
* datanodes.
*/
for (i = 0; i < num_params; i++)
{
int plen = strlen(paramTypes[i]) + 1;
memcpy(handle->outBuffer + handle->outEnd, paramTypes[i], plen);
handle->outEnd += plen;
pfree(paramTypes[i]);
}
pfree(paramTypes);
handle->in_extended_query = true;
return 0;
}
/*
* pgxc_node_send_bind
* Send BIND message down to the datanode.
*/
int
pgxc_node_send_bind(PGXCNodeHandle * handle, const char *portal,
const char *statement, int paramlen, char *params)
{
int pnameLen;
int stmtLen;
int paramCodeLen;
int paramValueLen;
int paramOutLen;
int msgLen;
/* Invalid connection state, return error */
if (handle->state != DN_CONNECTION_STATE_IDLE)
return EOF;
/* portal name size (allow NULL) */
pnameLen = portal ? strlen(portal) + 1 : 1;
/* statement name size (allow NULL) */
stmtLen = statement ? strlen(statement) + 1 : 1;
/* size of parameter codes array (always empty for now) */
paramCodeLen = 2;
/* size of parameter values array, 2 if no params */
paramValueLen = paramlen ? paramlen : 2;
/* size of output parameter codes array (always empty for now) */
paramOutLen = 2;
/* size + pnameLen + stmtLen + parameters */
msgLen = 4 + pnameLen + stmtLen + paramCodeLen + paramValueLen + paramOutLen;
/* msgType + msgLen */
if (ensure_out_buffer_capacity(handle->outEnd + 1 + msgLen, handle) != 0)
{
add_error_message(handle, "out of memory");
return EOF;
}
handle->outBuffer[handle->outEnd++] = 'B';
/* size */
msgLen = htonl(msgLen);
memcpy(handle->outBuffer + handle->outEnd, &msgLen, 4);
handle->outEnd += 4;
/* portal name */
if (portal)
{
memcpy(handle->outBuffer + handle->outEnd, portal, pnameLen);
handle->outEnd += pnameLen;
}
else
handle->outBuffer[handle->outEnd++] = '\0';
/* statement name */
if (statement)
{
memcpy(handle->outBuffer + handle->outEnd, statement, stmtLen);
handle->outEnd += stmtLen;
}
else
handle->outBuffer[handle->outEnd++] = '\0';
/* parameter codes (none) */
handle->outBuffer[handle->outEnd++] = 0;
handle->outBuffer[handle->outEnd++] = 0;
/* parameter values */
if (paramlen)
{
memcpy(handle->outBuffer + handle->outEnd, params, paramlen);
handle->outEnd += paramlen;
}
else
{
handle->outBuffer[handle->outEnd++] = 0;
handle->outBuffer[handle->outEnd++] = 0;
}
/* output parameter codes (none) */
handle->outBuffer[handle->outEnd++] = 0;
handle->outBuffer[handle->outEnd++] = 0;
handle->in_extended_query = true;
return 0;
}
/*
* pgxc_node_send_describe
* Send DESCRIBE message (portal or statement) down to the datanode.
*/
int
pgxc_node_send_describe(PGXCNodeHandle * handle, bool is_statement,
const char *name)
{
int nameLen;
int msgLen;
/* Invalid connection state, return error */
if (handle->state != DN_CONNECTION_STATE_IDLE)
return EOF;
/* statement or portal name size (allow NULL) */
nameLen = name ? strlen(name) + 1 : 1;
/* size + statement/portal + name */
msgLen = 4 + 1 + nameLen;
/* msgType + msgLen */
if (ensure_out_buffer_capacity(handle->outEnd + 1 + msgLen, handle) != 0)
{
add_error_message(handle, "out of memory");
return EOF;
}
handle->outBuffer[handle->outEnd++] = 'D';
/* size */
msgLen = htonl(msgLen);
memcpy(handle->outBuffer + handle->outEnd, &msgLen, 4);
handle->outEnd += 4;
/* statement/portal flag */
handle->outBuffer[handle->outEnd++] = is_statement ? 'S' : 'P';
/* object name */
if (name)
{
memcpy(handle->outBuffer + handle->outEnd, name, nameLen);
handle->outEnd += nameLen;
}
else
handle->outBuffer[handle->outEnd++] = '\0';
handle->in_extended_query = true;
return 0;
}
/*
* pgxc_node_send_close
* Send CLOSE message (portal or statement) down to the datanode.
*/
int
pgxc_node_send_close(PGXCNodeHandle * handle, bool is_statement,
const char *name)
{
/* statement or portal name size (allow NULL) */
int nameLen = name ? strlen(name) + 1 : 1;
/* size + statement/portal + name */
int msgLen = 4 + 1 + nameLen;
/* msgType + msgLen */
if (ensure_out_buffer_capacity(handle->outEnd + 1 + msgLen, handle) != 0)
{
add_error_message(handle, "out of memory");
return EOF;
}
handle->outBuffer[handle->outEnd++] = 'C';
/* size */
msgLen = htonl(msgLen);
memcpy(handle->outBuffer + handle->outEnd, &msgLen, 4);
handle->outEnd += 4;
/* statement/portal flag */
handle->outBuffer[handle->outEnd++] = is_statement ? 'S' : 'P';
/* object name */
if (name)
{
memcpy(handle->outBuffer + handle->outEnd, name, nameLen);
handle->outEnd += nameLen;
}
else
handle->outBuffer[handle->outEnd++] = '\0';
handle->in_extended_query = true;
return 0;
}
/*
* pgxc_node_send_execute
* Send EXECUTE message down to the datanode.
*/
int
pgxc_node_send_execute(PGXCNodeHandle * handle, const char *portal, int fetch)
{
/* portal name size (allow NULL) */
int pnameLen = portal ? strlen(portal) + 1 : 1;
/* size + pnameLen + fetchLen */
int msgLen = 4 + pnameLen + 4;
/* msgType + msgLen */
if (ensure_out_buffer_capacity(handle->outEnd + 1 + msgLen, handle) != 0)
{
add_error_message(handle, "out of memory");
return EOF;
}
handle->outBuffer[handle->outEnd++] = 'E';
/* size */
msgLen = htonl(msgLen);
memcpy(handle->outBuffer + handle->outEnd, &msgLen, 4);
handle->outEnd += 4;
/* portal name */
if (portal)
{
memcpy(handle->outBuffer + handle->outEnd, portal, pnameLen);
handle->outEnd += pnameLen;
}
else
handle->outBuffer[handle->outEnd++] = '\0';
/* fetch */
fetch = htonl(fetch);
memcpy(handle->outBuffer + handle->outEnd, &fetch, 4);
handle->outEnd += 4;
PGXCNodeSetConnectionState(handle, DN_CONNECTION_STATE_QUERY);
handle->in_extended_query = true;
return 0;
}
/*
* pgxc_node_send_flush
* Send FLUSH message down to the datanode.
*/
int
pgxc_node_send_flush(PGXCNodeHandle * handle)
{
/* size */
int msgLen = 4;
/* msgType + msgLen */
if (ensure_out_buffer_capacity(handle->outEnd + 1 + msgLen, handle) != 0)
{
add_error_message(handle, "out of memory");
return EOF;
}
handle->outBuffer[handle->outEnd++] = 'H';
/* size */
msgLen = htonl(msgLen);
memcpy(handle->outBuffer + handle->outEnd, &msgLen, 4);
handle->outEnd += 4;
handle->in_extended_query = true;
return pgxc_node_flush(handle);
}
/*
* pgxc_node_send_sync
* Send SYNC message down to the datanode.
*/
int
pgxc_node_send_sync(PGXCNodeHandle * handle)
{
/* size */
int msgLen = 4;
/* msgType + msgLen */
if (ensure_out_buffer_capacity(handle->outEnd + 1 + msgLen, handle) != 0)
{
add_error_message(handle, "out of memory");
return EOF;
}
handle->outBuffer[handle->outEnd++] = 'S';
/* size */
msgLen = htonl(msgLen);
memcpy(handle->outBuffer + handle->outEnd, &msgLen, 4);
handle->outEnd += 4;
handle->in_extended_query = false;
handle->needSync = false;
return pgxc_node_flush(handle);
}
/*
* pgxc_node_send_query_extended
* Send series of Extended Query protocol messages to the datanode.
*/
int
pgxc_node_send_query_extended(PGXCNodeHandle *handle, const char *query,
const char *statement, const char *portal,
int num_params, Oid *param_types,
int paramlen, char *params,
bool send_describe, int fetch_size)
{
/* NULL query indicates already prepared statement */
if (query)
if (pgxc_node_send_parse(handle, statement, query, num_params, param_types))
return EOF;
if (pgxc_node_send_bind(handle, portal, statement, paramlen, params))
return EOF;
if (send_describe)
if (pgxc_node_send_describe(handle, false, portal))
return EOF;
if (fetch_size >= 0)
if (pgxc_node_send_execute(handle, portal, fetch_size))
return EOF;
if (pgxc_node_send_flush(handle))
return EOF;
return 0;
}
/*
* pgxc_node_flush
* Flush all data from the output buffer of a node handle.
*
* This method won't return until connection buffer is empty or error occurs.
* To ensure all data are on the wire before waiting for a response.
*/
int
pgxc_node_flush(PGXCNodeHandle *handle)
{
while (handle->outEnd)
{
if (send_some(handle, handle->outEnd) < 0)
{
add_error_message(handle, "failed to send data to datanode");
/*
* before returning, also update the shared health
* status field to indicate that this node could be
* possibly unavailable.
*
* Note that this error could be due to a stale handle
* and it's possible that another backend might have
* already updated the health status OR the node
* might have already come back since the last disruption
*/
PoolPingNodeRecheck(handle->nodeoid);
return EOF;
}
}
return 0;
}
/*
* pgxc_node_send_query_internal
* Send the statement down to the PGXC node.
*/
static int
pgxc_node_send_query_internal(PGXCNodeHandle * handle, const char *query,
bool rollback)
{
int strLen;
int msgLen;
/*
* Its appropriate to send ROLLBACK commands on a failed connection, but
* for everything else we expect the connection to be in a sane state
*/
elog(DEBUG5, "pgxc_node_send_query - handle->state %d, node %s, query %s",
handle->state, handle->nodename, query);
if ((handle->state != DN_CONNECTION_STATE_IDLE) &&
!(handle->state == DN_CONNECTION_STATE_ERROR_FATAL && rollback))
return EOF;
strLen = strlen(query) + 1;
/* size + strlen */
msgLen = 4 + strLen;
/* msgType + msgLen */
if (ensure_out_buffer_capacity(handle->outEnd + 1 + msgLen, handle) != 0)
{
add_error_message(handle, "out of memory");
return EOF;
}
handle->outBuffer[handle->outEnd++] = 'Q';
msgLen = htonl(msgLen);
memcpy(handle->outBuffer + handle->outEnd, &msgLen, 4);
handle->outEnd += 4;
memcpy(handle->outBuffer + handle->outEnd, query, strLen);
handle->outEnd += strLen;
PGXCNodeSetConnectionState(handle, DN_CONNECTION_STATE_QUERY);
handle->in_extended_query = false;
return pgxc_node_flush(handle);
}
/*
* pgxc_node_send_rollback
* Send the rollback command to the remote node.
*
* XXX The only effect of the "rollback" is that we try sending the query
* even on invalid/failed connections (when everything else is prohibited).
*/
int
pgxc_node_send_rollback(PGXCNodeHandle *handle, const char *query)
{
return pgxc_node_send_query_internal(handle, query, true);
}
/*
* pgxc_node_send_query
* Send the query to the remote node.
*/
int
pgxc_node_send_query(PGXCNodeHandle *handle, const char *query)
{
return pgxc_node_send_query_internal(handle, query, false);
}
/*
* pgxc_node_send_gxid
* Send the GXID (global transaction ID) down to the remote node.
*/
int
pgxc_node_send_gxid(PGXCNodeHandle *handle, GlobalTransactionId gxid)
{
int msglen = 8;
/* Invalid connection state, return error */
if (handle->state != DN_CONNECTION_STATE_IDLE)
return EOF;
/* msgType + msgLen */
if (ensure_out_buffer_capacity(handle->outEnd + 1 + msglen, handle) != 0)
{
add_error_message(handle, "out of memory");
return EOF;
}
handle->outBuffer[handle->outEnd++] = 'g';
msglen = htonl(msglen);
memcpy(handle->outBuffer + handle->outEnd, &msglen, 4);
handle->outEnd += 4;
memcpy(handle->outBuffer + handle->outEnd, &gxid, sizeof
(TransactionId));
handle->outEnd += sizeof (TransactionId);
return 0;
}
/*
* pgxc_node_send_cmd_id
* Send the Command ID down to the remote node
*/
int
pgxc_node_send_cmd_id(PGXCNodeHandle *handle, CommandId cid)
{
int msglen = CMD_ID_MSG_LEN;
int i32;
/* No need to send command ID if its sending flag is not enabled */
if (!IsSendCommandId())
return 0;
/* Invalid connection state, return error */
if (handle->state != DN_CONNECTION_STATE_IDLE)
return EOF;
/* msgType + msgLen */
if (ensure_out_buffer_capacity(handle->outEnd + 1 + msglen, handle) != 0)
{
add_error_message(handle, "out of memory");
return EOF;
}
handle->outBuffer[handle->outEnd++] = 'M';
msglen = htonl(msglen);
memcpy(handle->outBuffer + handle->outEnd, &msglen, 4);
handle->outEnd += 4;
i32 = htonl(cid);
memcpy(handle->outBuffer + handle->outEnd, &i32, 4);
handle->outEnd += 4;
return 0;
}
/*
* pgxc_node_send_snapshot
* Send the snapshot down to the remote node.
*/
int
pgxc_node_send_snapshot(PGXCNodeHandle *handle, Snapshot snapshot)
{
int msglen;
int nval;
int i;
/* Invalid connection state, return error */
if (handle->state != DN_CONNECTION_STATE_IDLE)
return EOF;
/* calculate message length */
msglen = 20;
if (snapshot->xcnt > 0)
msglen += snapshot->xcnt * 4;
/* msgType + msgLen */
if (ensure_out_buffer_capacity(handle->outEnd + 1 + msglen, handle) != 0)
{
add_error_message(handle, "out of memory");
return EOF;
}
handle->outBuffer[handle->outEnd++] = 's';
msglen = htonl(msglen);
memcpy(handle->outBuffer + handle->outEnd, &msglen, 4);
handle->outEnd += 4;
memcpy(handle->outBuffer + handle->outEnd, &snapshot->xmin, sizeof (TransactionId));
handle->outEnd += sizeof (TransactionId);
memcpy(handle->outBuffer + handle->outEnd, &snapshot->xmax, sizeof (TransactionId));
handle->outEnd += sizeof (TransactionId);
memcpy(handle->outBuffer + handle->outEnd, &RecentGlobalXmin, sizeof (TransactionId));
handle->outEnd += sizeof (TransactionId);
nval = htonl(snapshot->xcnt);
memcpy(handle->outBuffer + handle->outEnd, &nval, 4);
handle->outEnd += 4;
for (i = 0; i < snapshot->xcnt; i++)
{
memcpy(handle->outBuffer + handle->outEnd, &snapshot->xip[i], sizeof
(TransactionId));
handle->outEnd += sizeof (TransactionId);
}
return 0;
}
/*
* pgxc_node_send_timestamp
* Send the timestamp down to the remote node
*/
int
pgxc_node_send_timestamp(PGXCNodeHandle *handle, TimestampTz timestamp)
{
int msglen = 12; /* 4 bytes for msglen and 8 bytes for timestamp (int64) */
uint32 n32;
int64 i = (int64) timestamp;
/* Invalid connection state, return error */
if (handle->state != DN_CONNECTION_STATE_IDLE)
return EOF;
/* msgType + msgLen */
if (ensure_out_buffer_capacity(handle->outEnd + 1 + msglen, handle) != 0)
{
add_error_message(handle, "out of memory");
return EOF;
}
handle->outBuffer[handle->outEnd++] = 't';
msglen = htonl(msglen);
memcpy(handle->outBuffer + handle->outEnd, &msglen, 4);
handle->outEnd += 4;
/* High order half first */
#ifdef INT64_IS_BUSTED
/* don't try a right shift of 32 on a 32-bit word */
n32 = (i < 0) ? -1 : 0;
#else
n32 = (uint32) (i >> 32);
#endif
n32 = htonl(n32);
memcpy(handle->outBuffer + handle->outEnd, &n32, 4);
handle->outEnd += 4;
/* Now the low order half */
n32 = (uint32) i;
n32 = htonl(n32);
memcpy(handle->outBuffer + handle->outEnd, &n32, 4);
handle->outEnd += 4;
return 0;
}
/*
* add_error_message
* Add a message to the list of errors to be returned back to the client
* at a convenient time.
*/
void
add_error_message(PGXCNodeHandle *handle, const char *message)
{
elog(LOG, "Remote node \"%s\", running with pid %d returned an error: %s",
handle->nodename, handle->backend_pid, message);
handle->transaction_status = 'E';
if (handle->error)
{
/* PGXCTODO append */
}
else
handle->error = pstrdup(message);
}
/* index of the last node returned by get_any_handled (round-robin) */
static int load_balancer = 0;
/*
* get_any_handle
* Get one of the specified nodes to query replicated data source.
*
* If session already owns one or more of requested datanode connections,
* the function returns one of those existing ones to avoid unnecessary
* pooler requests.
*
* Performs basic load balancing.
*/
PGXCNodeHandle *
get_any_handle(List *datanodelist)
{
ListCell *lc1;
int i, node;
/* sanity check */
Assert(list_length(datanodelist) > 0);
if (HandlesInvalidatePending)
if (DoInvalidateRemoteHandles())
ereport(ERROR,
(errcode(ERRCODE_QUERY_CANCELED),
errmsg("canceling transaction due to cluster configuration reset by administrator command")));
if (HandlesRefreshPending)
if (DoRefreshRemoteHandles())
ereport(ERROR,
(errcode(ERRCODE_QUERY_CANCELED),
errmsg("canceling transaction due to cluster configuration reset by administrator command")));
/* loop through local datanode handles */
for (i = 0, node = load_balancer; i < NumDataNodes; i++, node++)
{
/* At the moment node is an index in the array, and we may need to wrap it */
if (node >= NumDataNodes)
node -= NumDataNodes;
/* See if handle is already used */
if (dn_handles[node].sock != NO_SOCKET)
{
foreach(lc1, datanodelist)
{
if (lfirst_int(lc1) == node)
{
/*
* The node is in the list of requested nodes,
* set load_balancer for next time and return the handle
*/
load_balancer = node + 1;
return &dn_handles[node];
}
}
}
}
/*
* None of requested nodes is in use, need to get one from the pool.
* Choose one.
*/
for (i = 0, node = load_balancer; i < NumDataNodes; i++, node++)
{
/* At the moment node is an index in the array, and we may need to wrap it */
if (node >= NumDataNodes)
node -= NumDataNodes;
/* Look only at empty slots, we have already checked existing handles */
if (dn_handles[node].sock == NO_SOCKET)
{
foreach(lc1, datanodelist)
{
if (lfirst_int(lc1) == node)
{
/* The node is requested */
List *allocate = list_make1_int(node);
int *pids;
int *fds = PoolManagerGetConnections(allocate, NIL,
&pids);
PGXCNodeHandle *node_handle;
if (!fds)
{
Assert(pids != NULL);
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
errmsg("Failed to get pooled connections"),
errhint("This may happen because one or more nodes are "
"currently unreachable, either because of node or "
"network failure.\n Its also possible that the target node "
"may have hit the connection limit or the pooler is "
"configured with low connections.\n Please check "
"if all nodes are running fine and also review "
"max_connections and max_pool_size configuration "
"parameters")));
}
node_handle = &dn_handles[node];
pgxc_node_init(node_handle, fds[0], true, pids[0]);
datanode_count++;
elog(DEBUG1, "Established a connection with datanode \"%s\","
"remote backend PID %d, socket fd %d, global session %c",
node_handle->nodename, (int) pids[0], fds[0], 'T');
/*
* set load_balancer for next time and return the handle
*/
load_balancer = node + 1;
return &dn_handles[node];
}
}
}
}
/* We should not get here, one of the cases should be met */
Assert(false);
/* Keep compiler quiet */
return NULL;
}
/*
* get_handles
* Return array of node handles (PGXCNodeHandles) for requested nodes.
*
* If we don't have the handles in the pool, acquire from pool if needed.
*
* For datanodes, the specified list may be set to NIL, in which case we
* return handles for all datanodes.
*
* For coordinators, we do not acquire any handles when NIL list is used.
* Coordinator handles are needed only for transaction performing DDL.
*/
PGXCNodeAllHandles *
get_handles(List *datanodelist, List *coordlist, bool is_coord_only_query, bool is_global_session)
{
PGXCNodeAllHandles *result;
ListCell *node_list_item;
List *dn_allocate = NIL;
List *co_allocate = NIL;
PGXCNodeHandle *node_handle;
/* index of the result array */
int i = 0;
if (HandlesInvalidatePending)
if (DoInvalidateRemoteHandles())
ereport(ERROR,
(errcode(ERRCODE_QUERY_CANCELED),
errmsg("canceling transaction due to cluster configuration reset by administrator command")));
if (HandlesRefreshPending)
if (DoRefreshRemoteHandles())
ereport(ERROR,
(errcode(ERRCODE_QUERY_CANCELED),
errmsg("canceling transaction due to cluster configuration reset by administrator command")));
result = (PGXCNodeAllHandles *) palloc(sizeof(PGXCNodeAllHandles));
if (!result)
{
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory")));
}
result->primary_handle = NULL;
result->datanode_handles = NULL;
result->coord_handles = NULL;
result->co_conn_count = list_length(coordlist);
result->dn_conn_count = list_length(datanodelist);
/*
* Get Handles for Datanodes
* If node list is empty execute request on current nodes.
* It is also possible that the query has to be launched only on Coordinators.
*/
if (!is_coord_only_query)
{
if (list_length(datanodelist) == 0)
{
/*
* We do not have to zero the array - on success all items will be set
* to correct pointers, on error the array will be freed
*/
result->datanode_handles = (PGXCNodeHandle **)
palloc(NumDataNodes * sizeof(PGXCNodeHandle *));
if (!result->datanode_handles)
{
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory")));
}
for (i = 0; i < NumDataNodes; i++)
{
node_handle = &dn_handles[i];
result->datanode_handles[i] = node_handle;
if (node_handle->sock == NO_SOCKET)
dn_allocate = lappend_int(dn_allocate, i);
}
}
else
{
/*
* We do not have to zero the array - on success all items will be set
* to correct pointers, on error the array will be freed
*/
result->datanode_handles = (PGXCNodeHandle **)
palloc(list_length(datanodelist) * sizeof(PGXCNodeHandle *));
if (!result->datanode_handles)
{
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory")));
}
i = 0;
foreach(node_list_item, datanodelist)
{
int node = lfirst_int(node_list_item);
if (node < 0 || node >= NumDataNodes)
{
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("Invalid Datanode number")));
}
node_handle = &dn_handles[node];
result->datanode_handles[i++] = node_handle;
if (node_handle->sock == NO_SOCKET)
dn_allocate = lappend_int(dn_allocate, node);
}
}
}
/*
* Get Handles for Coordinators
* If node list is empty execute request on current nodes
* There are transactions where the Coordinator list is NULL Ex:COPY
*/
if (coordlist)
{
if (list_length(coordlist) == 0)
{
/*
* We do not have to zero the array - on success all items will be set
* to correct pointers, on error the array will be freed
*/
result->coord_handles = (PGXCNodeHandle **)palloc(NumCoords * sizeof(PGXCNodeHandle *));
if (!result->coord_handles)
{
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory")));
}
for (i = 0; i < NumCoords; i++)
{
node_handle = &co_handles[i];
result->coord_handles[i] = node_handle;
if (node_handle->sock == NO_SOCKET)
co_allocate = lappend_int(co_allocate, i);
}
}
else
{
/*
* We do not have to zero the array - on success all items will be set
* to correct pointers, on error the array will be freed
*/
result->coord_handles = (PGXCNodeHandle **)
palloc(list_length(coordlist) * sizeof(PGXCNodeHandle *));
if (!result->coord_handles)
{
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory")));
}
i = 0;
/* Some transactions do not need Coordinators, ex: COPY */
foreach(node_list_item, coordlist)
{
int node = lfirst_int(node_list_item);
if (node < 0 || node >= NumCoords)
{
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("Invalid coordinator number")));
}
node_handle = &co_handles[node];
result->coord_handles[i++] = node_handle;
if (node_handle->sock == NO_SOCKET)
co_allocate = lappend_int(co_allocate, node);
}
}
}
/*
* Pooler can get activated even if list of Coordinator or Datanode is NULL
* If both lists are NIL, we don't need to call Pooler.
*/
if (dn_allocate || co_allocate)
{
int j = 0;
int *pids;
int *fds = PoolManagerGetConnections(dn_allocate, co_allocate, &pids);
if (!fds)
{
if (coordlist)
if (result->coord_handles)
pfree(result->coord_handles);
if (datanodelist)
if (result->datanode_handles)
pfree(result->datanode_handles);
pfree(result);
if (dn_allocate)
list_free(dn_allocate);
if (co_allocate)
list_free(co_allocate);
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
errmsg("Failed to get pooled connections"),
errhint("This may happen because one or more nodes are "
"currently unreachable, either because of node or "
"network failure.\n Its also possible that the target node "
"may have hit the connection limit or the pooler is "
"configured with low connections.\n Please check "
"if all nodes are running fine and also review "
"max_connections and max_pool_size configuration "
"parameters")));
}
/* Initialisation for Datanodes */
if (dn_allocate)
{
foreach(node_list_item, dn_allocate)
{
int node = lfirst_int(node_list_item);
int fdsock = fds[j];
int be_pid = pids[j++];
if (node < 0 || node >= NumDataNodes)
{
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("Invalid Datanode number")));
}
node_handle = &dn_handles[node];
pgxc_node_init(node_handle, fdsock, is_global_session, be_pid);
dn_handles[node] = *node_handle;
datanode_count++;
elog(DEBUG1, "Established a connection with datanode \"%s\","
"remote backend PID %d, socket fd %d, global session %c",
node_handle->nodename, (int) be_pid, fdsock,
is_global_session ? 'T' : 'F');
}
}
/* Initialisation for Coordinators */
if (co_allocate)
{
foreach(node_list_item, co_allocate)
{
int node = lfirst_int(node_list_item);
int be_pid = pids[j];
int fdsock = fds[j++];
if (node < 0 || node >= NumCoords)
{
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("Invalid coordinator number")));
}
node_handle = &co_handles[node];
pgxc_node_init(node_handle, fdsock, is_global_session, be_pid);
co_handles[node] = *node_handle;
coord_count++;
elog(DEBUG1, "Established a connection with coordinator \"%s\","
"remote backend PID %d, socket fd %d, global session %c",
node_handle->nodename, (int) be_pid, fdsock,
is_global_session ? 'T' : 'F');
}
}
pfree(fds);
if (co_allocate)
list_free(co_allocate);
if (dn_allocate)
list_free(dn_allocate);
}
return result;
}
/*
* get_current_handles
* Return currently acquired handles.
*/
PGXCNodeAllHandles *
get_current_handles(void)
{
PGXCNodeAllHandles *result;
PGXCNodeHandle *node_handle;
int i;
result = (PGXCNodeAllHandles *) palloc(sizeof(PGXCNodeAllHandles));
if (!result)
{
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory")));
}
result->primary_handle = NULL;
result->co_conn_count = 0;
result->dn_conn_count = 0;
result->datanode_handles = (PGXCNodeHandle **)
palloc(NumDataNodes * sizeof(PGXCNodeHandle *));
if (!result->datanode_handles)
{
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory")));
}
for (i = 0; i < NumDataNodes; i++)
{
node_handle = &dn_handles[i];
if (node_handle->sock != NO_SOCKET)
result->datanode_handles[result->dn_conn_count++] = node_handle;
}
result->coord_handles = (PGXCNodeHandle **)
palloc(NumCoords * sizeof(PGXCNodeHandle *));
if (!result->coord_handles)
{
ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY),
errmsg("out of memory")));
}
for (i = 0; i < NumCoords; i++)
{
node_handle = &co_handles[i];
if (node_handle->sock != NO_SOCKET)
result->coord_handles[result->co_conn_count++] = node_handle;
}
return result;
}
/*
* pfree_pgxc_all_handles
* Free memory allocated for the PGXCNodeAllHandles structure.
*/
void
pfree_pgxc_all_handles(PGXCNodeAllHandles *pgxc_handles)
{
if (!pgxc_handles)
return;
if (pgxc_handles->primary_handle)
pfree(pgxc_handles->primary_handle);
if (pgxc_handles->datanode_handles)
pfree(pgxc_handles->datanode_handles);
if (pgxc_handles->coord_handles)
pfree(pgxc_handles->coord_handles);
pfree(pgxc_handles);
}
/*
* PGXCNodeGetNodeId
* Lookup index of the requested node (by OID) in the cached handles.
*
* Optionally, the node type may be restricted using the second parameter.
* If the type is PGXC_NODE_COORDINATOR, we only look in coordinator list.
* If the node is PGXC_NODE_DATANODE, we only look in datanode list.
*
* For other values (assume PGXC_NODE_NONE) we search for both node types,
* and then also return the actual node type in the second parameter.
*/
int
PGXCNodeGetNodeId(Oid nodeoid, char *node_type)
{
int i;
/* First check datanodes, they referenced more often */
if (node_type == NULL || *node_type != PGXC_NODE_COORDINATOR)
{
for (i = 0; i < NumDataNodes; i++)
{
if (dn_handles[i].nodeoid == nodeoid)
{
if (node_type)
*node_type = PGXC_NODE_DATANODE;
return i;
}
}
}
/* Then check coordinators */
if (node_type == NULL || *node_type != PGXC_NODE_DATANODE)
{
for (i = 0; i < NumCoords; i++)
{
if (co_handles[i].nodeoid == nodeoid)
{
if (node_type)
*node_type = PGXC_NODE_COORDINATOR;
return i;
}
}
}
/* Not found, have caller handling it */
if (node_type)
*node_type = PGXC_NODE_NONE;
return -1;
}
/*
* PGXCNodeGetNodeOid
* Look at the data cached for handles and return node Oid.
*
* XXX Unlike PGXCNodeGetNodeId, this requires node type parameter.
*/
Oid
PGXCNodeGetNodeOid(int nodeid, char node_type)
{
PGXCNodeHandle *handles;
switch (node_type)
{
case PGXC_NODE_COORDINATOR:
handles = co_handles;
break;
case PGXC_NODE_DATANODE:
handles = dn_handles;
break;
default:
/* Should not happen */
Assert(0);
return InvalidOid;
}
return handles[nodeid].nodeoid;
}
/*
* pgxc_node_str
* get the name of the current node
*/
Datum
pgxc_node_str(PG_FUNCTION_ARGS)
{
PG_RETURN_TEXT_P(cstring_to_text(PGXCNodeName));
}
/*
* PGXCNodeGetNodeIdFromName
* Return position of the node (specified by name) in handles array.
*/
int
PGXCNodeGetNodeIdFromName(char *node_name, char *node_type)
{
char *nm;
Oid nodeoid;
if (node_name == NULL)
{
if (node_type)
*node_type = PGXC_NODE_NONE;
return -1;
}
nm = str_tolower(node_name, strlen(node_name), DEFAULT_COLLATION_OID);
nodeoid = get_pgxc_nodeoid(nm);
pfree(nm);
if (!OidIsValid(nodeoid))
{
if (node_type)
*node_type = PGXC_NODE_NONE;
return -1;
}
return PGXCNodeGetNodeId(nodeoid, node_type);
}
/*
* paramlist_delete_param
* Delete parameter with the specified name from the parameter list.
*/
static List *
paramlist_delete_param(List *param_list, const char *name)
{
ListCell *cur_item;
ListCell *prev_item;
prev_item = NULL;
cur_item = list_head(param_list);
while (cur_item != NULL)
{
ParamEntry *entry = (ParamEntry *) lfirst(cur_item);
if (strcmp(NameStr(entry->name), name) == 0)
{
/* cur_item must be removed */
param_list = list_delete_cell(param_list, cur_item, prev_item);
pfree(entry);
if (prev_item)
cur_item = lnext(prev_item);
else
cur_item = list_head(param_list);
}
else
{
prev_item = cur_item;
cur_item = lnext(prev_item);
}
}
return param_list;
}
/*
* PGXCNodeSetParam
* Remember new value of a session/transaction parameter.
*
* We'll set this parameter value for new connections to remote nodes.
*/
void
PGXCNodeSetParam(bool local, const char *name, const char *value, int flags)
{
List *param_list;
MemoryContext oldcontext;
/* Get the target hash table and invalidate command string */
if (local)
{
param_list = local_param_list;
if (local_params)
resetStringInfo(local_params);
oldcontext = MemoryContextSwitchTo(TopTransactionContext);
}
else
{
param_list = session_param_list;
if (session_params)
resetStringInfo(session_params);
oldcontext = MemoryContextSwitchTo(TopMemoryContext);
}
param_list = paramlist_delete_param(param_list, name);
if (value)
{
ParamEntry *entry;
entry = (ParamEntry *) palloc(sizeof (ParamEntry));
strlcpy((char *) (&entry->name), name, NAMEDATALEN);
strlcpy((char *) (&entry->value), value, NAMEDATALEN);
entry->flags = flags;
param_list = lappend(param_list, entry);
}
/*
* Special case for
*
* RESET SESSION AUTHORIZATION
* SET SESSION AUTHORIZATION TO DEFAULT
*
* We must also forget any SET ROLE commands since RESET SESSION
* AUTHORIZATION also resets current role to session default
*/
if ((strcmp(name, "session_authorization") == 0) && (value == NULL))
param_list = paramlist_delete_param(param_list, "role");
if (local)
local_param_list = param_list;
else
session_param_list = param_list;
MemoryContextSwitchTo(oldcontext);
}
/*
* PGXCNodeResetParams
* Forget all transaction (or session too) parameters.
*/
void
PGXCNodeResetParams(bool only_local)
{
if (!only_local && session_param_list)
{
/* need to explicitly pfree session stuff, it is in TopMemoryContext */
list_free_deep(session_param_list);
session_param_list = NIL;
if (session_params)
{
pfree(session_params->data);
pfree(session_params);
session_params = NULL;
}
}
/*
* no need to explicitly destroy the local_param_list and local_params,
* it will gone with the transaction memory context.
*/
local_param_list = NIL;
local_params = NULL;
}
/*
* get_set_command
* Construct a command setting all parameters from a given list.
*/
static void
get_set_command(List *param_list, StringInfo command, bool local)
{
ListCell *lc;
if (param_list == NIL)
return;
foreach (lc, param_list)
{
ParamEntry *entry = (ParamEntry *) lfirst(lc);
const char *value = NameStr(entry->value);
if (strlen(value) == 0)
value = "''";
value = quote_guc_value(value, entry->flags);
appendStringInfo(command, "SET %s %s TO %s;", local ? "LOCAL" : "",
NameStr(entry->name), value);
}
}
/*
* PGXCNodeGetSessionParamStr
* Returns SET commands needed to initialize remote session.
*
* The SET command may already be built and valid (in the session_params),
* in which case we simply return it. Otherwise we build if from session
* parameter list.
*
* To support "Distributed Session" machinery, the coordinator should
* generate and send a distributed session identifier to remote nodes.
* Generate it here (simply as nodename_PID).
*
* We always define a parameter with PID of the parent process (which is
* this backend).
*/
char *
PGXCNodeGetSessionParamStr(void)
{
/*
* If no session parameters are set and this is a coordinator node, we
* need to set global_session anyway, even if there are no other params.
*
* We do not want this string to simply disappear, so create it in the
* TopMemoryContext.
*/
if (session_params == NULL)
{
MemoryContext oldcontext = MemoryContextSwitchTo(TopMemoryContext);
session_params = makeStringInfo();
MemoryContextSwitchTo(oldcontext);
}
/* If the parameter string is empty, build it up. */
if (session_params->len == 0)
{
if (IS_PGXC_COORDINATOR)
appendStringInfo(session_params, "SET global_session TO %s_%d;",
PGXCNodeName, MyProcPid);
get_set_command(session_param_list, session_params, false);
appendStringInfo(session_params, "SET parentPGXCPid TO %d;",
MyProcPid);
}
return session_params->len == 0 ? NULL : session_params->data;
}
/*
* PGXCNodeGetTransactionParamStr
* Returns SET commands needed to initialize transaction on a remote node.
*
* The command may already be built and valid (in local_params StringInfo), in
* which case we return it right away. Otherwise build it up.
*/
char *
PGXCNodeGetTransactionParamStr(void)
{
/* If no local parameters defined there is nothing to return */
if (local_param_list == NIL)
return NULL;
/*
* If the StringInfo is not allocated yed, do it in TopTransactionContext.
*/
if (local_params == NULL)
{
MemoryContext oldcontext = MemoryContextSwitchTo(TopTransactionContext);
local_params = makeStringInfo();
MemoryContextSwitchTo(oldcontext);
}
/*
* If the parameter string is empty, it was reset in PGXCNodeSetParam. So
* recompute it, using the current local_param_list (we know it's not
* empty, otherwise we wound't get here through the first condition).
*/
if (local_params->len == 0)
{
get_set_command(local_param_list, local_params, true);
}
return local_params->len == 0 ? NULL : local_params->data;
}
/*
* pgxc_node_set_query
* Send down specified query, discard all responses until ReadyForQuery.
*/
void
pgxc_node_set_query(PGXCNodeHandle *handle, const char *set_query)
{
pgxc_node_send_query(handle, set_query);
/*
* Now read responses until ReadyForQuery.
* XXX We may need to handle possible errors here.
*/
for (;;)
{
char msgtype;
int msglen;
char *msg;
/*
* If we are in the process of shutting down, we
* may be rolling back, and the buffer may contain other messages.
* We want to avoid a procarray exception
* as well as an error stack overflow.
*/
if (proc_exit_inprogress)
PGXCNodeSetConnectionState(handle, DN_CONNECTION_STATE_ERROR_FATAL);
/* don't read from from the connection if there is a fatal error */
if (handle->state == DN_CONNECTION_STATE_ERROR_FATAL)
break;
/* No data available, read more */
if (!HAS_MESSAGE_BUFFERED(handle))
{
pgxc_node_receive(1, &handle, NULL);
continue;
}
msgtype = get_message(handle, &msglen, &msg);
/*
* Ignore any response except ErrorResponse and ReadyForQuery
*/
if (msgtype == 'E') /* ErrorResponse */
{
handle->error = pstrdup(msg);
PGXCNodeSetConnectionState(handle, DN_CONNECTION_STATE_ERROR_FATAL);
break;
}
if (msgtype == 'Z') /* ReadyForQuery */
{
handle->transaction_status = msg[0];
PGXCNodeSetConnectionState(handle, DN_CONNECTION_STATE_IDLE);
handle->combiner = NULL;
break;
}
}
}
void
RequestInvalidateRemoteHandles(void)
{
HandlesInvalidatePending = true;
}
void
RequestRefreshRemoteHandles(void)
{
HandlesRefreshPending = true;
}
bool
PoolerMessagesPending(void)
{
if (HandlesRefreshPending)
return true;
return false;
}
/*
* For all handles, mark as they are not in use and discard pending input/output
*/
static bool
DoInvalidateRemoteHandles(void)
{
int i;
PGXCNodeHandle *handle;
bool result = false;
HandlesInvalidatePending = false;
HandlesRefreshPending = false;
for (i = 0; i < NumCoords; i++)
{
handle = &co_handles[i];
if (handle->sock != NO_SOCKET)
result = true;
handle->sock = NO_SOCKET;
handle->inStart = handle->inEnd = handle->inCursor = 0;
handle->outEnd = 0;
}
for (i = 0; i < NumDataNodes; i++)
{
handle = &dn_handles[i];
if (handle->sock != NO_SOCKET)
result = true;
handle->sock = NO_SOCKET;
handle->inStart = handle->inEnd = handle->inCursor = 0;
handle->outEnd = 0;
}
InitMultinodeExecutor(true);
return result;
}
/*
* Diff handles using shmem, and remove ALTERed handles
*/
static bool
DoRefreshRemoteHandles(void)
{
List *altered = NIL, *deleted = NIL, *added = NIL;
Oid *coOids, *dnOids;
int numCoords, numDNodes, total_nodes;
bool res = true;
HandlesRefreshPending = false;
PgxcNodeGetOids(&coOids, &dnOids, &numCoords, &numDNodes, false);
total_nodes = numCoords + numDNodes;
if (total_nodes > 0)
{
int i;
List *shmoids = NIL;
Oid *allOids = (Oid *)palloc(total_nodes * sizeof(Oid));
/* build array with Oids of all nodes (coordinators first) */
memcpy(allOids, coOids, numCoords * sizeof(Oid));
memcpy(allOids + numCoords, dnOids, numDNodes * sizeof(Oid));
LWLockAcquire(NodeTableLock, LW_SHARED);
for (i = 0; i < total_nodes; i++)
{
NodeDefinition *nodeDef;
PGXCNodeHandle *handle;
int nid;
Oid nodeoid;
char ntype = PGXC_NODE_NONE;
nodeoid = allOids[i];
shmoids = lappend_oid(shmoids, nodeoid);
nodeDef = PgxcNodeGetDefinition(nodeoid);
/*
* identify an entry with this nodeoid. If found
* compare the name/host/port entries. If the name is
* same and other info is different, it's an ALTER.
* If the local entry does not exist in the shmem, it's
* a DELETE. If the entry from shmem does not exist
* locally, it's an ADDITION
*/
nid = PGXCNodeGetNodeId(nodeoid, &ntype);
if (nid == -1)
{
/* a new node has been added to the shmem */
added = lappend_oid(added, nodeoid);
elog(LOG, "Node added: name (%s) host (%s) port (%d)",
NameStr(nodeDef->nodename), NameStr(nodeDef->nodehost),
nodeDef->nodeport);
}
else
{
if (ntype == PGXC_NODE_COORDINATOR)
handle = &co_handles[nid];
else if (ntype == PGXC_NODE_DATANODE)
handle = &dn_handles[nid];
else
elog(ERROR, "Node with non-existent node type!");
/*
* compare name, host, port to see if this node
* has been ALTERed
*/
if (strncmp(handle->nodename, NameStr(nodeDef->nodename), NAMEDATALEN) != 0 ||
strncmp(handle->nodehost, NameStr(nodeDef->nodehost), NAMEDATALEN) != 0 ||
handle->nodeport != nodeDef->nodeport)
{
elog(LOG, "Node altered: old name (%s) old host (%s) old port (%d)"
" new name (%s) new host (%s) new port (%d)",
handle->nodename, handle->nodehost, handle->nodeport,
NameStr(nodeDef->nodename), NameStr(nodeDef->nodehost),
nodeDef->nodeport);
altered = lappend_oid(altered, nodeoid);
}
/* else do nothing */
}
pfree(nodeDef);
}
/*
* Any entry in backend area but not in shmem means that it has
* been deleted
*/
for (i = 0; i < NumCoords; i++)
{
PGXCNodeHandle *handle = &co_handles[i];
Oid nodeoid = handle->nodeoid;
if (!list_member_oid(shmoids, nodeoid))
{
deleted = lappend_oid(deleted, nodeoid);
elog(LOG, "Node deleted: name (%s) host (%s) port (%d)",
handle->nodename, handle->nodehost, handle->nodeport);
}
}
for (i = 0; i < NumDataNodes; i++)
{
PGXCNodeHandle *handle = &dn_handles[i];
Oid nodeoid = handle->nodeoid;
if (!list_member_oid(shmoids, nodeoid))
{
deleted = lappend_oid(deleted, nodeoid);
elog(LOG, "Node deleted: name (%s) host (%s) port (%d)",
handle->nodename, handle->nodehost, handle->nodeport);
}
}
LWLockRelease(NodeTableLock);
/* Release palloc'ed memory */
pfree(coOids);
pfree(dnOids);
pfree(allOids);
list_free(shmoids);
}
if (deleted != NIL || added != NIL)
{
elog(LOG, "Nodes added/deleted. Reload needed!");
res = false;
}
if (altered == NIL)
{
elog(LOG, "No nodes altered. Returning");
res = true;
}
else
PgxcNodeRefreshBackendHandlesShmem(altered);
list_free(altered);
list_free(added);
list_free(deleted);
return res;
}
void
PGXCNodeSetConnectionState(PGXCNodeHandle *handle, DNConnectionState new_state)
{
elog(DEBUG5, "Changing connection state for node %s, old state %d, "
"new state %d", handle->nodename, handle->state, new_state);
handle->state = new_state;
}
/*
* Do a "Diff" of backend NODE metadata and the one present in catalog
*
* We do this in order to identify if we should do a destructive
* cleanup or just invalidation of some specific handles
*/
bool
PgxcNodeDiffBackendHandles(List **nodes_alter,
List **nodes_delete, List **nodes_add)
{
Relation rel;
HeapScanDesc scan;
HeapTuple tuple;
int i;
List *altered = NIL, *added = NIL, *deleted = NIL;
List *catoids = NIL;
PGXCNodeHandle *handle;
Oid nodeoid;
bool res = true;
LWLockAcquire(NodeTableLock, LW_SHARED);
rel = heap_open(PgxcNodeRelationId, AccessShareLock);
scan = heap_beginscan(rel, SnapshotSelf, 0, NULL);
while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
{
Form_pgxc_node nodeForm = (Form_pgxc_node) GETSTRUCT(tuple);
int nid;
Oid nodeoid;
char ntype = PGXC_NODE_NONE;
nodeoid = HeapTupleGetOid(tuple);
catoids = lappend_oid(catoids, nodeoid);
/*
* identify an entry with this nodeoid. If found
* compare the name/host/port entries. If the name is
* same and other info is different, it's an ALTER.
* If the local entry does not exist in the catalog, it's
* a DELETE. If the entry from catalog does not exist
* locally, it's an ADDITION
*/
nid = PGXCNodeGetNodeId(nodeoid, &ntype);
if (nid == -1)
{
/* a new node has been added to the catalog */
added = lappend_oid(added, nodeoid);
elog(LOG, "Node added: name (%s) host (%s) port (%d)",
NameStr(nodeForm->node_name), NameStr(nodeForm->node_host),
nodeForm->node_port);
}
else
{
if (ntype == PGXC_NODE_COORDINATOR)
handle = &co_handles[nid];
else if (ntype == PGXC_NODE_DATANODE)
handle = &dn_handles[nid];
else
elog(ERROR, "Node with non-existent node type!");
/*
* compare name, host, port to see if this node
* has been ALTERed
*/
if (strncmp(handle->nodename, NameStr(nodeForm->node_name), NAMEDATALEN)
!= 0 ||
strncmp(handle->nodehost, NameStr(nodeForm->node_host), NAMEDATALEN)
!= 0 ||
handle->nodeport != nodeForm->node_port)
{
elog(LOG, "Node altered: old name (%s) old host (%s) old port (%d)"
" new name (%s) new host (%s) new port (%d)",
handle->nodename, handle->nodehost, handle->nodeport,
NameStr(nodeForm->node_name), NameStr(nodeForm->node_host),
nodeForm->node_port);
/*
* If this node itself is being altered, then we need to
* resort to a reload. Check so..
*/
if (pg_strcasecmp(PGXCNodeName,
NameStr(nodeForm->node_name)) == 0)
{
res = false;
}
altered = lappend_oid(altered, nodeoid);
}
/* else do nothing */
}
}
heap_endscan(scan);
/*
* Any entry in backend area but not in catalog means that it has
* been deleted
*/
for (i = 0; i < NumCoords; i++)
{
handle = &co_handles[i];
nodeoid = handle->nodeoid;
if (!list_member_oid(catoids, nodeoid))
{
deleted = lappend_oid(deleted, nodeoid);
elog(LOG, "Node deleted: name (%s) host (%s) port (%d)",
handle->nodename, handle->nodehost, handle->nodeport);
}
}
for (i = 0; i < NumDataNodes; i++)
{
handle = &dn_handles[i];
nodeoid = handle->nodeoid;
if (!list_member_oid(catoids, nodeoid))
{
deleted = lappend_oid(deleted, nodeoid);
elog(LOG, "Node deleted: name (%s) host (%s) port (%d)",
handle->nodename, handle->nodehost, handle->nodeport);
}
}
heap_close(rel, AccessShareLock);
LWLockRelease(NodeTableLock);
if (nodes_alter)
*nodes_alter = altered;
if (nodes_delete)
*nodes_delete = deleted;
if (nodes_add)
*nodes_add = added;
if (catoids)
list_free(catoids);
return res;
}
/*
* Refresh specific backend handles associated with
* nodes in the "nodes_alter" list below
*
* The handles are refreshed using shared memory
*/
void
PgxcNodeRefreshBackendHandlesShmem(List *nodes_alter)
{
ListCell *lc;
Oid nodeoid;
int nid;
PGXCNodeHandle *handle = NULL;
foreach(lc, nodes_alter)
{
char ntype = PGXC_NODE_NONE;
NodeDefinition *nodedef;
nodeoid = lfirst_oid(lc);
nid = PGXCNodeGetNodeId(nodeoid, &ntype);
if (nid == -1)
elog(ERROR, "Looks like node metadata changed again");
else
{
if (ntype == PGXC_NODE_COORDINATOR)
handle = &co_handles[nid];
else if (ntype == PGXC_NODE_DATANODE)
handle = &dn_handles[nid];
else
elog(ERROR, "Node with non-existent node type!");
}
/*
* Update the local backend handle data with data from catalog
* Free the handle first..
*/
pgxc_node_free(handle);
elog(LOG, "Backend (%u), Node (%s) updated locally",
MyBackendId, handle->nodename);
nodedef = PgxcNodeGetDefinition(nodeoid);
strncpy(handle->nodename, NameStr(nodedef->nodename), NAMEDATALEN);
strncpy(handle->nodehost, NameStr(nodedef->nodehost), NAMEDATALEN);
handle->nodeport = nodedef->nodeport;
pfree(nodedef);
}
return;
}
void
HandlePoolerMessages(void)
{
if (HandlesRefreshPending)
{
DoRefreshRemoteHandles();
elog(LOG, "Backend (%u), doing handles refresh",
MyBackendId);
}
return;
}
|