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
|
/*-------------------------------------------------------------------------
*
* pglogical_sync.c
* table synchronization functions
*
* Copyright (c) 2015, PostgreSQL Global Development Group
*
* IDENTIFICATION
* pglogical_sync.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <unistd.h>
#ifdef WIN32
#include <process.h>
#else
#include <sys/wait.h>
#endif
#include "libpq-fe.h"
#include "miscadmin.h"
#include "access/genam.h"
#include "access/hash.h"
#include "access/heapam.h"
#include "access/skey.h"
#include "access/stratnum.h"
#include "access/xact.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "commands/dbcommands.h"
#include "commands/tablecmds.h"
#include "lib/stringinfo.h"
#include "utils/memutils.h"
#include "nodes/makefuncs.h"
#include "nodes/parsenodes.h"
#include "pgstat.h"
#include "replication/origin.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/proc.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/pg_lsn.h"
#include "utils/rel.h"
#include "utils/resowner.h"
#include "pglogical_relcache.h"
#include "pglogical_repset.h"
#include "pglogical_rpc.h"
#include "pglogical_sync.h"
#include "pglogical_worker.h"
#include "pglogical.h"
#define CATALOG_LOCAL_SYNC_STATUS "local_sync_status"
#if PG_VERSION_NUM < 90500
#define PGDUMP_BINARY "pglogical_dump"
#else
#define PGDUMP_BINARY "pg_dump"
#endif
#define PGRESTORE_BINARY "pg_restore"
#define Natts_local_sync_state 6
#define Anum_sync_kind 1
#define Anum_sync_subid 2
#define Anum_sync_nspname 3
#define Anum_sync_relname 4
#define Anum_sync_status 5
#define Anum_sync_statuslsn 6
void PGDLLEXPORT pglogical_sync_main(Datum main_arg);
static PGLogicalSyncWorker *MySyncWorker = NULL;
#ifdef WIN32
static int exec_cmd_win32(const char *cmd, char *cmdargv[]);
#endif
/*
* Run a command and wait for it to exit, then return its exit code
* in the same format as waitpid() including on Windows.
*
* Does not elog(ERROR).
*
* 'cmd' must be a full relative or absolute path to the executable to
* start. The PATH is not searched.
*
* Preserves each argument in cmdargv as a discrete argument to the child
* process. The first entry in cmdargv is passed as the child process's
* argv[0], so the first "real" argument begins at index 1.
*
* Uses the current environment and working directory.
*
* Note that if we elog(ERROR) or elog(FATAL) here we won't kill the
* child proc.
*/
static int
exec_cmd(const char *cmd, char *cmdargv[])
{
pid_t pid;
int stat;
/* Fire off execv in child */
fflush(stdout);
fflush(stderr);
#ifndef WIN32
if ((pid = fork()) == 0)
{
if (execv(cmd, cmdargv) < 0)
{
ereport(ERROR,
(errmsg("could not execute \"%s\": %m", cmd)));
/* We're already in the child process here, can't return */
exit(1);
}
}
if (waitpid(pid, &stat, 0) != pid)
stat = -1;
#else
stat = exec_cmd_win32(cmd, cmdargv);
#endif
return stat;
}
static void
get_pg_executable(char *cmdname, char *cmdbuf)
{
uint32 version;
if (find_other_exec_version(my_exec_path, cmdname, &version, cmdbuf))
elog(ERROR, "pglogical subscriber init failed to find %s relative to binary %s",
cmdname, my_exec_path);
if (version / 100 != PG_VERSION_NUM / 100)
elog(ERROR, "pglogical subscriber init found %s with wrong major version %d.%d, expected %d.%d",
cmdname, version / 100 / 100, version / 100 % 100,
PG_VERSION_NUM / 100 / 100, PG_VERSION_NUM / 100 % 100);
}
static void
dump_structure(PGLogicalSubscription *sub, const char *destfile,
const char *snapshot)
{
char *dsn;
char *err_msg;
char pg_dump[MAXPGPATH];
char *cmdargv[20];
int cmdargc = 0;
bool has_pgl_origin;
StringInfoData s;
dsn = pgl_get_connstr((char *) sub->origin_if->dsn, NULL, NULL, &err_msg);
if (dsn == NULL)
elog(ERROR, "invalid connection string \"%s\": %s",
sub->origin_if->dsn, err_msg);
get_pg_executable(PGDUMP_BINARY, pg_dump);
cmdargv[cmdargc++] = pg_dump;
/* custom format */
cmdargv[cmdargc++] = "-Fc";
/* schema only */
cmdargv[cmdargc++] = "-s";
/* snapshot */
initStringInfo(&s);
appendStringInfo(&s, "--snapshot=%s", snapshot);
cmdargv[cmdargc++] = pstrdup(s.data);
resetStringInfo(&s);
/* Dumping database, filter out our extension. */
appendStringInfo(&s, "--exclude-schema=%s", EXTENSION_NAME);
cmdargv[cmdargc++] = pstrdup(s.data);
resetStringInfo(&s);
/* Skip the pglogical_origin if it exists locally. */
StartTransactionCommand();
has_pgl_origin = OidIsValid(LookupExplicitNamespace("pglogical_origin",
true));
CommitTransactionCommand();
if (has_pgl_origin)
{
appendStringInfo(&s, "--exclude-schema=%s", "pglogical_origin");
cmdargv[cmdargc++] = pstrdup(s.data);
resetStringInfo(&s);
}
/* destination file */
appendStringInfo(&s, "--file=%s", destfile);
cmdargv[cmdargc++] = pstrdup(s.data);
resetStringInfo(&s);
/* connection string */
appendStringInfo(&s, "--dbname=%s", dsn);
cmdargv[cmdargc++] = pstrdup(s.data);
resetStringInfo(&s);
free(dsn);
cmdargv[cmdargc++] = NULL;
if (exec_cmd(pg_dump, cmdargv) != 0)
ereport(ERROR,
(errcode_for_file_access(),
errmsg("could not execute pg_dump (\"%s\"): %m",
pg_dump)));
}
static void
restore_structure(PGLogicalSubscription *sub, const char *srcfile,
const char *section)
{
char *dsn;
char *err_msg;
char pg_restore[MAXPGPATH];
char *cmdargv[20];
int cmdargc = 0;
StringInfoData s;
dsn = pgl_get_connstr((char *) sub->target_if->dsn, NULL,
"-cpglogical.subscription_schema_restore=true",
&err_msg);
if (dsn == NULL)
elog(ERROR, "invalid connection string \"%s\": %s",
sub->target_if->dsn, err_msg);
get_pg_executable(PGRESTORE_BINARY, pg_restore);
cmdargv[cmdargc++] = pg_restore;
/* section */
if (section)
{
initStringInfo(&s);
appendStringInfo(&s, "--section=%s", section);
cmdargv[cmdargc++] = pstrdup(s.data);
resetStringInfo(&s);
}
/* stop execution on any error */
cmdargv[cmdargc++] = "--exit-on-error";
/* apply everything in single tx */
cmdargv[cmdargc++] = "-1";
/* connection string */
initStringInfo(&s);
appendStringInfo(&s, "--dbname=%s", dsn);
cmdargv[cmdargc++] = pstrdup(s.data);
free(dsn);
/* source file */
cmdargv[cmdargc++] = pstrdup(srcfile);
cmdargv[cmdargc++] = NULL;
if (exec_cmd(pg_restore, cmdargv) != 0)
ereport(ERROR,
(errcode_for_file_access(),
errmsg("could not execute pg_restore (\"%s\"): %m",
pg_restore)));
}
/*
* Create slot and get the exported snapshot.
*
* This will try to recreate slot if already exists and not active.
*
* The reported LSN is the confirmed flush LSN at the point the slot reached
* consistency and exported its snapshot.
*/
static char *
ensure_replication_slot_snapshot(PGconn *sql_conn, PGconn *repl_conn,
char *slot_name, bool use_failover_slot,
XLogRecPtr *lsn)
{
PGresult *res;
StringInfoData query;
char *snapshot;
retry:
initStringInfo(&query);
appendStringInfo(&query, "CREATE_REPLICATION_SLOT \"%s\" LOGICAL %s%s",
slot_name, "pglogical_output",
use_failover_slot ? " FAILOVER" : "");
res = PQexec(repl_conn, query.data);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
const char *sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
/*
* If our slot already exist but is not used, it's leftover from
* previous unsucessful attempt to synchronize table, try dropping
* it and recreating.
*/
if (sqlstate &&
strcmp(sqlstate, "42710" /*ERRCODE_DUPLICATE_OBJECT*/) == 0 &&
!pglogical_remote_slot_active(sql_conn, slot_name))
{
pfree(query.data);
PQclear(res);
pglogical_drop_remote_slot(sql_conn, slot_name);
goto retry;
}
elog(ERROR, "could not create replication slot on provider: %s\n",
PQresultErrorMessage(res));
}
*lsn = DatumGetLSN(DirectFunctionCall1Coll(pg_lsn_in, InvalidOid,
CStringGetDatum(PQgetvalue(res, 0, 1))));
snapshot = pstrdup(PQgetvalue(res, 0, 2));
PQclear(res);
return snapshot;
}
/*
* Get or create replication origin for a given slot.
*/
static RepOriginId
ensure_replication_origin(char *slot_name)
{
RepOriginId origin = replorigin_by_name(slot_name, true);
if (origin == InvalidRepOriginId)
origin = replorigin_create(slot_name);
return origin;
}
/*
* Transaction management for COPY.
*/
static void
start_copy_origin_tx(PGconn *conn, const char *snapshot)
{
PGresult *res;
char *s;
const char *setup_query =
"BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY;\n"
"SET DATESTYLE = ISO;\n"
"SET INTERVALSTYLE = POSTGRES;\n"
"SET extra_float_digits TO 3;\n"
"SET statement_timeout = 0;\n"
"SET lock_timeout = 0;\n";
StringInfoData query;
initStringInfo(&query);
appendStringInfoString(&query, setup_query);
if (snapshot)
{
s = PQescapeLiteral(conn, snapshot, strlen(snapshot));
appendStringInfo(&query, "SET TRANSACTION SNAPSHOT %s;\n", s);
}
res = PQexec(conn, query.data);
if (PQresultStatus(res) != PGRES_COMMAND_OK)
elog(ERROR, "BEGIN on origin node failed: %s",
PQresultErrorMessage(res));
PQclear(res);
}
static void
start_copy_target_tx(PGconn *conn, const char *origin_name)
{
PGresult *res;
char *s;
const char *setup_query =
"BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED;\n"
"SET session_replication_role = 'replica';\n"
"SET DATESTYLE = ISO;\n"
"SET INTERVALSTYLE = POSTGRES;\n"
"SET extra_float_digits TO 3;\n"
"SET statement_timeout = 0;\n"
"SET lock_timeout = 0;\n";
StringInfoData query;
initStringInfo(&query);
/*
* Set correct origin if target db supports it.
* We must do this before starting the transaction otherwise the status
* code bellow would get much more complicated.
*/
if (PQserverVersion(conn) >= 90500)
{
s = PQescapeLiteral(conn, origin_name, strlen(origin_name));
appendStringInfo(&query,
"SELECT pg_catalog.pg_replication_origin_session_setup(%s);\n",
s);
PQfreemem(s);
}
appendStringInfoString(&query, setup_query);
res = PQexec(conn, query.data);
if (PQresultStatus(res) != PGRES_COMMAND_OK)
elog(ERROR, "BEGIN on target node failed: %s",
PQresultErrorMessage(res));
PQclear(res);
}
static void
finish_copy_origin_tx(PGconn *conn)
{
PGresult *res;
/* Close the transaction and connection on origin node. */
res = PQexec(conn, "ROLLBACK");
if (PQresultStatus(res) != PGRES_COMMAND_OK)
elog(WARNING, "ROLLBACK on origin node failed: %s",
PQresultErrorMessage(res));
PQclear(res);
PQfinish(conn);
}
static void
finish_copy_target_tx(PGconn *conn)
{
PGresult *res;
/* Close the transaction and connection on target node. */
res = PQexec(conn, "COMMIT");
if (PQresultStatus(res) != PGRES_COMMAND_OK)
elog(ERROR, "COMMIT on target node failed: %s",
PQresultErrorMessage(res));
PQclear(res);
/*
* Resetting the origin explicitly before the backend exits will help
* prevent races with other accesses to the same replication origin.
*/
if (PQserverVersion(conn) >= 90500)
{
res = PQexec(conn, "SELECT pg_catalog.pg_replication_origin_session_reset();\n");
if (PQresultStatus(res) != PGRES_TUPLES_OK)
elog(WARNING, "Resetting session origin on target node failed: %s",
PQresultErrorMessage(res));
PQclear(res);
}
PQfinish(conn);
}
static int
physatt_in_attmap(PGLogicalRelation *rel, int attid)
{
AttrNumber i;
for (i = 0; i < rel->natts; i++)
if (rel->attmap[i] == attid)
return i;
return -1;
}
/*
* Create list of columns for COPY based on logical relation mapping.
*/
static List *
make_copy_attnamelist(PGLogicalRelation *rel)
{
List *attnamelist = NIL;
TupleDesc desc = RelationGetDescr(rel->rel);
int attnum;
for (attnum = 0; attnum < desc->natts; attnum++)
{
int remoteattnum = physatt_in_attmap(rel, attnum);
/* Skip dropped attributes. */
if (TupleDescAttr(desc,attnum)->attisdropped)
continue;
if (remoteattnum < 0)
continue;
attnamelist = lappend(attnamelist,
makeString(rel->attnames[remoteattnum]));
}
return attnamelist;
}
/*
* COPY single table over wire.
*/
static void
copy_table_data(PGconn *origin_conn, PGconn *target_conn,
PGLogicalRemoteRel *remoterel, List *replication_sets)
{
PGLogicalRelation *rel;
PGresult *res;
int bytes;
char *copybuf;
List *attnamelist;
ListCell *lc;
bool first;
StringInfoData query;
StringInfoData attlist;
MemoryContext curctx = CurrentMemoryContext,
oldctx;
/* Build the relation map. */
StartTransactionCommand();
oldctx = MemoryContextSwitchTo(curctx);
pglogical_relation_cache_updater(remoterel);
rel = pglogical_relation_open(remoterel->relid, AccessShareLock);
attnamelist = make_copy_attnamelist(rel);
initStringInfo(&attlist);
first = true;
foreach (lc, attnamelist)
{
char *attname = strVal(lfirst(lc));
if (first)
first = false;
else
appendStringInfoString(&attlist, ",");
appendStringInfoString(&attlist,
PQescapeIdentifier(origin_conn, attname,
strlen(attname)));
}
MemoryContextSwitchTo(oldctx);
pglogical_relation_close(rel, AccessShareLock);
CommitTransactionCommand();
/* Build COPY TO query. */
initStringInfo(&query);
appendStringInfoString(&query, "COPY ");
/*
* If the table is row-filtered we need to run query over the table
* to execute the filter.
*/
if (remoterel->hasRowFilter)
{
StringInfoData relname;
StringInfoData repsetarr;
ListCell *lc1;
initStringInfo(&relname);
appendStringInfo(&relname, "%s.%s",
PQescapeIdentifier(origin_conn, remoterel->nspname,
strlen(remoterel->nspname)),
PQescapeIdentifier(origin_conn, remoterel->relname,
strlen(remoterel->relname)));
initStringInfo(&repsetarr);
first = true;
foreach (lc1, replication_sets)
{
char *repset_name = lfirst(lc1);
if (first)
first = false;
else
appendStringInfoChar(&repsetarr, ',');
appendStringInfo(&repsetarr, "%s",
PQescapeLiteral(origin_conn, repset_name,
strlen(repset_name)));
}
appendStringInfo(&query,
"(SELECT %s FROM pglogical.table_data_filtered(NULL::%s, %s::regclass, ARRAY[%s])) ",
list_length(attnamelist) ? attlist.data : "*",
relname.data,
PQescapeLiteral(origin_conn, relname.data, relname.len),
repsetarr.data);
}
else
{
/* Otherwise just copy the table. */
appendStringInfo(&query, "%s.%s ",
PQescapeIdentifier(origin_conn, remoterel->nspname,
strlen(remoterel->nspname)),
PQescapeIdentifier(origin_conn, remoterel->relname,
strlen(remoterel->relname)));
if (list_length(attnamelist))
appendStringInfo(&query, "(%s) ", attlist.data);
}
appendStringInfoString(&query, "TO stdout");
/* Execute COPY TO. */
res = PQexec(origin_conn, query.data);
if (PQresultStatus(res) != PGRES_COPY_OUT)
{
ereport(ERROR,
(errmsg("table copy failed"),
errdetail("Query '%s': %s", query.data,
PQerrorMessage(origin_conn))));
}
/* Build COPY FROM query. */
resetStringInfo(&query);
appendStringInfo(&query, "COPY %s.%s ",
PQescapeIdentifier(origin_conn, remoterel->nspname,
strlen(remoterel->nspname)),
PQescapeIdentifier(origin_conn, remoterel->relname,
strlen(remoterel->relname)));
if (list_length(attnamelist))
appendStringInfo(&query, "(%s) ", attlist.data);
appendStringInfoString(&query, "FROM stdin");
/* Execute COPY FROM. */
res = PQexec(target_conn, query.data);
if (PQresultStatus(res) != PGRES_COPY_IN)
{
ereport(ERROR,
(errmsg("table copy failed"),
errdetail("Query '%s': %s", query.data,
PQerrorMessage(origin_conn))));
}
while ((bytes = PQgetCopyData(origin_conn, ©buf, false)) > 0)
{
if (PQputCopyData(target_conn, copybuf, bytes) != 1)
{
ereport(ERROR,
(errmsg("writing to target table failed"),
errdetail("destination connection reported: %s",
PQerrorMessage(target_conn))));
}
PQfreemem(copybuf);
CHECK_FOR_INTERRUPTS();
}
if (bytes != -1)
{
ereport(ERROR,
(errmsg("reading from origin table failed"),
errdetail("source connection returned %d: %s",
bytes, PQerrorMessage(origin_conn))));
}
/* Send local finish */
if (PQputCopyEnd(target_conn, NULL) != 1)
{
ereport(ERROR,
(errmsg("sending copy-completion to destination connection failed"),
errdetail("destination connection reported: %s",
PQerrorMessage(target_conn))));
}
PQclear(res);
elog(INFO, "finished synchronization of data for table %s.%s",
remoterel->nspname, remoterel->relname);
}
/*
* Copy data from origin node to target node.
*
* Creates new connection to origin and target.
*/
static void
copy_tables_data(char *sub_name, const char *origin_dsn,
const char *target_dsn, const char *origin_snapshot,
List *tables, List *replication_sets,
const char *origin_name)
{
PGconn *origin_conn;
PGconn *target_conn;
ListCell *lc;
/* Connect to origin node. */
origin_conn = pglogical_connect(origin_dsn, sub_name, "copy");
start_copy_origin_tx(origin_conn, origin_snapshot);
/* Connect to target node. */
target_conn = pglogical_connect(target_dsn, sub_name, "copy");
start_copy_target_tx(target_conn, origin_name);
/* Copy every table. */
foreach (lc, tables)
{
RangeVar *rv = lfirst(lc);
PGLogicalRemoteRel *remoterel;
remoterel = pg_logical_get_remote_repset_table(origin_conn, rv,
replication_sets);
copy_table_data(origin_conn, target_conn, remoterel, replication_sets);
CHECK_FOR_INTERRUPTS();
}
/* Finish the transactions and disconnect. */
finish_copy_origin_tx(origin_conn);
finish_copy_target_tx(target_conn);
}
/*
* Copy data from origin node to target node.
*
* Creates new connection to origin and target.
*
* This is basically same as the copy_tables_data, but it can't be easily
* merged to single function because we need to get list of tables here after
* the transaction is bound to a snapshot.
*/
static List *
copy_replication_sets_data(char *sub_name, const char *origin_dsn,
const char *target_dsn,
const char *origin_snapshot,
List *replication_sets, const char *origin_name)
{
PGconn *origin_conn;
PGconn *target_conn;
List *tables;
ListCell *lc;
/* Connect to origin node. */
origin_conn = pglogical_connect(origin_dsn, sub_name, "copy");
start_copy_origin_tx(origin_conn, origin_snapshot);
/* Get tables to copy from origin node. */
tables = pg_logical_get_remote_repset_tables(origin_conn,
replication_sets);
/* Connect to target node. */
target_conn = pglogical_connect(target_dsn, sub_name, "copy");
start_copy_target_tx(target_conn, origin_name);
/* Copy every table. */
foreach (lc, tables)
{
PGLogicalRemoteRel *remoterel = lfirst(lc);
copy_table_data(origin_conn, target_conn, remoterel, replication_sets);
CHECK_FOR_INTERRUPTS();
}
/* Finish the transactions and disconnect. */
finish_copy_origin_tx(origin_conn);
finish_copy_target_tx(target_conn);
return tables;
}
static void
pglogical_sync_worker_cleanup(PGLogicalSubscription *sub)
{
PGconn *origin_conn;
/* Drop the slot on the remote side. */
origin_conn = pglogical_connect(sub->origin_if->dsn, sub->name,
"cleanup");
/* Wait for slot to be free. */
while (!got_SIGTERM)
{
int rc;
if (!pglogical_remote_slot_active(origin_conn, sub->slot_name))
break;
rc = WaitLatch(&MyProc->procLatch,
WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
1000L);
ResetLatch(&MyProc->procLatch);
/* emergency bailout if postmaster has died */
if (rc & WL_POSTMASTER_DEATH)
proc_exit(1);
}
pglogical_drop_remote_slot(origin_conn, sub->slot_name);
PQfinish(origin_conn);
/* Drop the origin tracking locally. */
if (replorigin_session_origin != InvalidRepOriginId)
{
replorigin_session_reset();
#if PG_VERSION_NUM >= 140000
replorigin_drop_by_name(sub->slot_name, true, true);
#else
replorigin_drop(replorigin_session_origin, true);
#endif
replorigin_session_origin = InvalidRepOriginId;
}
}
static void
pglogical_sync_worker_cleanup_error_cb(int code, Datum arg)
{
PGLogicalSubscription *sub = (PGLogicalSubscription *) DatumGetPointer(arg);
pglogical_sync_worker_cleanup(sub);
}
static void
pglogical_sync_tmpfile_cleanup_cb(int code, Datum arg)
{
const char *tmpfile = DatumGetCString(arg);
if (unlink(tmpfile) != 0 && errno != ENOENT)
elog(WARNING, "Failed to clean up pglogical temporary dump file \"%s\" on exit/error: %m",
tmpfile);
}
void
pglogical_sync_subscription(PGLogicalSubscription *sub)
{
PGLogicalSyncStatus *sync;
XLogRecPtr lsn;
char status;
MemoryContext myctx,
oldctx;
/* We need our own context for keeping things between transactions. */
myctx = AllocSetContextCreate(CurrentMemoryContext,
"pglogical_sync_subscription cxt",
ALLOCSET_DEFAULT_SIZES);
StartTransactionCommand();
oldctx = MemoryContextSwitchTo(myctx);
sync = get_subscription_sync_status(sub->id, false);
MemoryContextSwitchTo(oldctx);
CommitTransactionCommand();
status = sync->status;
switch (status)
{
/* Already synced, nothing to do except cleanup. */
case SYNC_STATUS_READY:
MemoryContextDelete(myctx);
return;
/* We can recover from crashes during these. */
case SYNC_STATUS_INIT:
case SYNC_STATUS_CATCHUP:
break;
default:
elog(ERROR,
"subscriber %s initialization failed during nonrecoverable step (%c), please try the setup again",
sub->name, status);
break;
}
if (status == SYNC_STATUS_INIT)
{
PGconn *origin_conn;
PGconn *origin_conn_repl;
RepOriginId originid;
char *snapshot;
bool use_failover_slot = false;
elog(INFO, "initializing subscriber %s", sub->name);
origin_conn = pglogical_connect(sub->origin_if->dsn,
sub->name, "snap");
/* 2QPG9.6 and 2QPG11 support failover slots */
#if defined(SECONDQ_VERSION_NUM) && PG_VERSION_NUM < 120000
use_failover_slot =
pglogical_remote_function_exists(origin_conn, "pg_catalog",
"pg_create_logical_replication_slot",
-1,
"failover");
#endif
origin_conn_repl = pglogical_connect_replica(sub->origin_if->dsn,
sub->name, "snap");
snapshot = ensure_replication_slot_snapshot(origin_conn,
origin_conn_repl,
sub->slot_name,
use_failover_slot, &lsn);
PQfinish(origin_conn);
PG_ENSURE_ERROR_CLEANUP(pglogical_sync_worker_cleanup_error_cb,
PointerGetDatum(sub));
{
char tmpfile[MAXPGPATH];
snprintf(tmpfile, MAXPGPATH, "%s/pglogical-%d.dump",
pglogical_temp_directory, MyProcPid);
canonicalize_path(tmpfile);
PG_ENSURE_ERROR_CLEANUP(pglogical_sync_tmpfile_cleanup_cb,
CStringGetDatum(tmpfile));
{
#if PG_VERSION_NUM >= 90500
Relation replorigin_rel;
#endif
StartTransactionCommand();
originid = ensure_replication_origin(sub->slot_name);
elog(DEBUG3, "advancing origin with oid %u for forwarded row to %X/%X during subscription sync",
originid,
(uint32)(XactLastCommitEnd>>32), (uint32)XactLastCommitEnd);
#if PG_VERSION_NUM >= 90500
replorigin_rel = table_open(ReplicationOriginRelationId, RowExclusiveLock);
#endif
replorigin_advance(originid, lsn, XactLastCommitEnd, true,
true);
#if PG_VERSION_NUM >= 90500
table_close(replorigin_rel, RowExclusiveLock);
#endif
CommitTransactionCommand();
if (SyncKindStructure(sync->kind))
{
elog(INFO, "synchronizing structure");
status = SYNC_STATUS_STRUCTURE;
StartTransactionCommand();
set_subscription_sync_status(sub->id, status);
CommitTransactionCommand();
/* Dump structure to temp storage. */
dump_structure(sub, tmpfile, snapshot);
/* Restore base pre-data structure (types, tables, etc). */
restore_structure(sub, tmpfile, "pre-data");
}
/* Copy data. */
if (SyncKindData(sync->kind))
{
List *tables;
ListCell *lc;
elog(INFO, "synchronizing data");
status = SYNC_STATUS_DATA;
StartTransactionCommand();
set_subscription_sync_status(sub->id, status);
CommitTransactionCommand();
tables = copy_replication_sets_data(sub->name,
sub->origin_if->dsn,
sub->target_if->dsn,
snapshot,
sub->replication_sets,
sub->slot_name);
/* Store info about all the synchronized tables. */
StartTransactionCommand();
foreach (lc, tables)
{
PGLogicalRemoteRel *remoterel = lfirst(lc);
PGLogicalSyncStatus *oldsync;
oldsync = get_table_sync_status(sub->id,
remoterel->nspname,
remoterel->relname, true);
if (oldsync)
{
set_table_sync_status(sub->id, remoterel->nspname,
remoterel->relname,
SYNC_STATUS_READY,
lsn);
}
else
{
PGLogicalSyncStatus newsync;
newsync.kind = SYNC_KIND_FULL;
newsync.subid = sub->id;
namestrcpy(&newsync.nspname, remoterel->nspname);
namestrcpy(&newsync.relname, remoterel->relname);
newsync.status = SYNC_STATUS_READY;
newsync.statuslsn = lsn;
create_local_sync_status(&newsync);
}
}
CommitTransactionCommand();
}
/* Restore post-data structure (indexes, constraints, etc). */
if (SyncKindStructure(sync->kind))
{
elog(INFO, "synchronizing constraints");
status = SYNC_STATUS_CONSTRAINTS;
StartTransactionCommand();
set_subscription_sync_status(sub->id, status);
CommitTransactionCommand();
restore_structure(sub, tmpfile, "post-data");
}
}
PG_END_ENSURE_ERROR_CLEANUP(pglogical_sync_tmpfile_cleanup_cb,
CStringGetDatum(tmpfile));
pglogical_sync_tmpfile_cleanup_cb(0,
CStringGetDatum(tmpfile));
}
PG_END_ENSURE_ERROR_CLEANUP(pglogical_sync_worker_cleanup_error_cb,
PointerGetDatum(sub));
PQfinish(origin_conn_repl);
status = SYNC_STATUS_CATCHUP;
StartTransactionCommand();
set_subscription_sync_status(sub->id, status);
CommitTransactionCommand();
}
if (status == SYNC_STATUS_CATCHUP)
{
/* Nothing to do here yet. */
status = SYNC_STATUS_READY;
StartTransactionCommand();
set_subscription_sync_status(sub->id, status);
CommitTransactionCommand();
elog(INFO, "finished synchronization of subscriber %s, ready to enter normal replication", sub->name);
}
MemoryContextDelete(myctx);
}
char
pglogical_sync_table(PGLogicalSubscription *sub, RangeVar *table,
XLogRecPtr *status_lsn)
{
PGconn *origin_conn_repl, *origin_conn;
RepOriginId originid;
char *snapshot;
PGLogicalSyncStatus *sync;
StartTransactionCommand();
/* Sanity check. */
sync = get_subscription_sync_status(sub->id, false);
if (sync->status != SYNC_STATUS_READY)
{
elog(ERROR,
"subscriber %s is not ready, cannot synchronzie individual tables", sub->name);
}
/* Check current state of the table. */
sync = get_table_sync_status(sub->id, table->schemaname, table->relname, false);
*status_lsn = sync->statuslsn;
/* Already synchronized, nothing to do here. */
if (sync->status == SYNC_STATUS_READY ||
sync->status == SYNC_STATUS_SYNCDONE)
return sync->status;
/* If previous sync attempt failed, we need to start from beginning. */
if (sync->status != SYNC_STATUS_INIT)
set_table_sync_status(sub->id, table->schemaname, table->relname,
SYNC_STATUS_INIT, InvalidXLogRecPtr);
CommitTransactionCommand();
origin_conn_repl = pglogical_connect_replica(sub->origin_if->dsn,
sub->name, "copy");
origin_conn = pglogical_connect(sub->origin_if->dsn, sub->name, "copy_slot");
snapshot = ensure_replication_slot_snapshot(origin_conn, origin_conn_repl,
sub->slot_name, false,
status_lsn);
PQfinish(origin_conn);
/* Make sure we cleanup the slot if something goes wrong. */
PG_ENSURE_ERROR_CLEANUP(pglogical_sync_worker_cleanup_error_cb,
PointerGetDatum(sub));
{
#if PG_VERSION_NUM >= 90500
Relation replorigin_rel;
#endif
StartTransactionCommand();
originid = ensure_replication_origin(sub->slot_name);
elog(DEBUG2, "advancing origin %s (oid %u) for forwarded row to %X/%X after sync error",
MySubscription->slot_name, originid,
(uint32)(XactLastCommitEnd>>32), (uint32)XactLastCommitEnd);
#if PG_VERSION_NUM >= 90500
replorigin_rel = table_open(ReplicationOriginRelationId, RowExclusiveLock);
#endif
replorigin_advance(originid, *status_lsn, XactLastCommitEnd, true,
true);
#if PG_VERSION_NUM >= 90500
table_close(replorigin_rel, RowExclusiveLock);
#endif
set_table_sync_status(sub->id, table->schemaname, table->relname,
SYNC_STATUS_DATA, *status_lsn);
CommitTransactionCommand();
/* Copy data. */
copy_tables_data(sub->name, sub->origin_if->dsn,sub->target_if->dsn,
snapshot, list_make1(table), sub->replication_sets,
sub->slot_name);
}
PG_END_ENSURE_ERROR_CLEANUP(pglogical_sync_worker_cleanup_error_cb,
PointerGetDatum(sub));
PQfinish(origin_conn_repl);
return SYNC_STATUS_SYNCWAIT;
}
void
pglogical_sync_worker_finish(void)
{
PGLogicalWorker *apply;
/*
* Commit any outstanding transaction. This is the usual case, unless
* there was nothing to do for the table.
*/
if (IsTransactionState())
{
CommitTransactionCommand();
pgstat_report_stat(false);
}
/* And flush all writes. */
XLogFlush(GetXLogWriteRecPtr());
StartTransactionCommand();
pglogical_sync_worker_cleanup(MySubscription);
CommitTransactionCommand();
/*
* In case there is apply process running, it might be waiting
* for the table status change so tell it to check.
*/
LWLockAcquire(PGLogicalCtx->lock, LW_EXCLUSIVE);
apply = pglogical_apply_find(MyPGLogicalWorker->dboid,
MyApplyWorker->subid);
if (pglogical_worker_running(apply))
SetLatch(&apply->proc->procLatch);
LWLockRelease(PGLogicalCtx->lock);
elog(LOG, "finished sync of table %s.%s for subscriber %s",
NameStr(MySyncWorker->nspname), NameStr(MySyncWorker->relname),
MySubscription->name);
}
void
pglogical_sync_main(Datum main_arg)
{
int slot = DatumGetInt32(main_arg);
PGconn *streamConn;
RepOriginId originid;
XLogRecPtr lsn;
XLogRecPtr status_lsn;
StringInfoData slot_name;
RangeVar *copytable = NULL;
MemoryContext saved_ctx;
char *tablename;
char status;
/* Setup shmem. */
pglogical_worker_attach(slot, PGLOGICAL_WORKER_SYNC);
MySyncWorker = &MyPGLogicalWorker->worker.sync;
MyApplyWorker = &MySyncWorker->apply;
/* Attach to dsm segment. */
Assert(CurrentResourceOwner == NULL);
CurrentResourceOwner = ResourceOwnerCreate(NULL, "pglogical sync");
/* Setup synchronous commit according to the user's wishes */
SetConfigOption("synchronous_commit",
pglogical_synchronous_commit ? "local" : "off",
PGC_BACKEND, PGC_S_OVERRIDE); /* other context? */
/* Run as replica session replication role. */
SetConfigOption("session_replication_role", "replica",
PGC_SUSET, PGC_S_OVERRIDE); /* other context? */
/*
* Disable function body checks during replay. That's necessary because a)
* the creator of the function might have had it disabled b) the function
* might be search_path dependant and we don't fix the contents of
* functions.
*/
SetConfigOption("check_function_bodies", "off",
PGC_INTERNAL, PGC_S_OVERRIDE);
StartTransactionCommand();
saved_ctx = MemoryContextSwitchTo(TopMemoryContext);
MySubscription = get_subscription(MySyncWorker->apply.subid);
MemoryContextSwitchTo(saved_ctx);
CommitTransactionCommand();
copytable = makeRangeVar(NameStr(MySyncWorker->nspname),
NameStr(MySyncWorker->relname), -1);
tablename = quote_qualified_identifier(copytable->schemaname,
copytable->relname);
initStringInfo(&slot_name);
appendStringInfo(&slot_name, "%s_%08x", MySubscription->slot_name,
DatumGetUInt32(hash_any((unsigned char *) tablename,
strlen(tablename))));
MySubscription->slot_name = slot_name.data;
elog(LOG, "starting sync of table %s.%s for subscriber %s",
copytable->schemaname, copytable->relname, MySubscription->name);
elog(DEBUG1, "connecting to provider %s, dsn %s",
MySubscription->origin_if->name, MySubscription->origin_if->dsn);
/* Do the initial sync first. */
status = pglogical_sync_table(MySubscription, copytable, &status_lsn);
if (status == SYNC_STATUS_SYNCDONE || status == SYNC_STATUS_READY)
{
pglogical_sync_worker_finish();
proc_exit(0);
}
/* Wait for ack from the main apply thread. */
StartTransactionCommand();
set_table_sync_status(MySubscription->id, copytable->schemaname,
copytable->relname, SYNC_STATUS_SYNCWAIT,
status_lsn);
CommitTransactionCommand();
wait_for_sync_status_change(MySubscription->id, copytable->schemaname,
copytable->relname, SYNC_STATUS_CATCHUP,
&lsn);
Assert(lsn == status_lsn);
/* Setup the origin and get the starting position for the replication. */
StartTransactionCommand();
originid = replorigin_by_name(MySubscription->slot_name, false);
elog(DEBUG2, "setting origin %s (oid %u) for subscription sync",
MySubscription->slot_name, originid);
PGLreplorigin_session_setup(originid);
replorigin_session_origin = originid;
Assert(status_lsn == replorigin_session_get_progress(false));
/*
* In case there is nothing to catchup, finish immediately.
* Note pglogical_sync_worker_finish() will commit.
*/
if (status_lsn >= MyApplyWorker->replay_stop_lsn)
{
/* Mark local table as done. */
set_table_sync_status(MyApplyWorker->subid,
NameStr(MyPGLogicalWorker->worker.sync.nspname),
NameStr(MyPGLogicalWorker->worker.sync.relname),
SYNC_STATUS_SYNCDONE, status_lsn);
pglogical_sync_worker_finish();
proc_exit(0);
}
CommitTransactionCommand();
/* Start the replication. */
streamConn = pglogical_connect_replica(MySubscription->origin_if->dsn,
MySubscription->name, "catchup");
/*
* IDENTIFY_SYSTEM sets up some internal state on walsender so call it even
* if we don't (yet) want to use any of the results.
*/
pglogical_identify_system(streamConn, NULL, NULL, NULL, NULL);
pglogical_start_replication(streamConn, MySubscription->slot_name,
status_lsn, "all", NULL, tablename,
MySubscription->force_text_transfer);
/* Leave it to standard apply code to do the replication. */
apply_work(streamConn);
PQfinish(streamConn);
/*
* We should only get here if we received sigTERM, which in case of
* sync worker is not expected.
*/
proc_exit(1);
}
/* Catalog access */
/* Create subscription sync status record in catalog. */
void
create_local_sync_status(PGLogicalSyncStatus *sync)
{
RangeVar *rv;
Relation rel;
TupleDesc tupDesc;
HeapTuple tup;
Datum values[Natts_local_sync_state];
bool nulls[Natts_local_sync_state];
rv = makeRangeVar(EXTENSION_NAME, CATALOG_LOCAL_SYNC_STATUS, -1);
rel = table_openrv(rv, RowExclusiveLock);
tupDesc = RelationGetDescr(rel);
/* Form a tuple. */
memset(nulls, false, sizeof(nulls));
values[Anum_sync_kind - 1] = CharGetDatum(sync->kind);
values[Anum_sync_subid - 1] = ObjectIdGetDatum(sync->subid);
if (sync->nspname.data[0])
values[Anum_sync_nspname - 1] = NameGetDatum(&sync->nspname);
else
nulls[Anum_sync_nspname - 1] = true;
if (sync->relname.data[0])
values[Anum_sync_relname - 1] = NameGetDatum(&sync->relname);
else
nulls[Anum_sync_relname - 1] = true;
values[Anum_sync_status - 1] = CharGetDatum(sync->status);
values[Anum_sync_statuslsn - 1] = LSNGetDatum(sync->statuslsn);
tup = heap_form_tuple(tupDesc, values, nulls);
/* Insert the tuple to the catalog. */
CatalogTupleInsert(rel, tup);
/* Cleanup. */
heap_freetuple(tup);
table_close(rel, RowExclusiveLock);
}
/* Remove subscription sync status record from catalog. */
void
drop_subscription_sync_status(Oid subid)
{
RangeVar *rv;
Relation rel;
SysScanDesc scan;
HeapTuple tuple;
ScanKeyData key[1];
rv = makeRangeVar(EXTENSION_NAME, CATALOG_LOCAL_SYNC_STATUS, -1);
rel = table_openrv(rv, RowExclusiveLock);
ScanKeyInit(&key[0],
Anum_sync_subid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(subid));
scan = systable_beginscan(rel, 0, true, NULL, 1, key);
/* Remove the tuples. */
while (HeapTupleIsValid(tuple = systable_getnext(scan)))
simple_heap_delete(rel, &tuple->t_self);
/* Cleanup. */
systable_endscan(scan);
table_close(rel, RowExclusiveLock);
}
static PGLogicalSyncStatus *
syncstatus_fromtuple(HeapTuple tuple, TupleDesc desc)
{
PGLogicalSyncStatus *sync;
Datum d;
bool isnull;
sync = (PGLogicalSyncStatus *) palloc0(sizeof(PGLogicalSyncStatus));
d = fastgetattr(tuple, Anum_sync_kind, desc, &isnull);
Assert(!isnull);
sync->kind = DatumGetChar(d);
d = fastgetattr(tuple, Anum_sync_subid, desc, &isnull);
Assert(!isnull);
sync->subid = DatumGetObjectId(d);
d = fastgetattr(tuple, Anum_sync_nspname, desc, &isnull);
if (!isnull)
namestrcpy(&sync->nspname, NameStr(*DatumGetName(d)));
d = fastgetattr(tuple, Anum_sync_relname, desc, &isnull);
if (!isnull)
namestrcpy(&sync->relname, NameStr(*DatumGetName(d)));
d = fastgetattr(tuple, Anum_sync_status, desc, &isnull);
Assert(!isnull);
sync->status = DatumGetChar(d);
d = fastgetattr(tuple, Anum_sync_statuslsn, desc, &isnull);
Assert(!isnull);
sync->statuslsn = DatumGetLSN(d);
return sync;
}
/* Get the sync status for a subscription. */
PGLogicalSyncStatus *
get_subscription_sync_status(Oid subid, bool missing_ok)
{
PGLogicalSyncStatus *sync;
RangeVar *rv;
Relation rel;
SysScanDesc scan;
HeapTuple tuple;
ScanKeyData key[1];
TupleDesc tupDesc;
rv = makeRangeVar(EXTENSION_NAME, CATALOG_LOCAL_SYNC_STATUS, -1);
rel = table_openrv(rv, RowExclusiveLock);
tupDesc = RelationGetDescr(rel);
ScanKeyInit(&key[0],
Anum_sync_subid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(subid));
scan = systable_beginscan(rel, 0, true, NULL, 1, key);
while (HeapTupleIsValid(tuple = systable_getnext(scan)))
{
if (pgl_heap_attisnull(tuple, Anum_sync_nspname, NULL) &&
pgl_heap_attisnull(tuple, Anum_sync_relname, NULL))
break;
}
if (!HeapTupleIsValid(tuple))
{
if (missing_ok)
{
systable_endscan(scan);
table_close(rel, RowExclusiveLock);
return NULL;
}
elog(ERROR, "subscription %u status not found", subid);
}
sync = syncstatus_fromtuple(tuple, tupDesc);
systable_endscan(scan);
table_close(rel, RowExclusiveLock);
return sync;
}
/* Set the sync status for a subscription. */
void
set_subscription_sync_status(Oid subid, char status)
{
RangeVar *rv;
Relation rel;
TupleDesc tupDesc;
SysScanDesc scan;
HeapTuple oldtup,
newtup;
ScanKeyData key[1];
Datum values[Natts_local_sync_state];
bool nulls[Natts_local_sync_state];
bool replaces[Natts_local_sync_state];
rv = makeRangeVar(EXTENSION_NAME, CATALOG_LOCAL_SYNC_STATUS, -1);
rel = table_openrv(rv, RowExclusiveLock);
tupDesc = RelationGetDescr(rel);
ScanKeyInit(&key[0],
Anum_sync_subid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(subid));
scan = systable_beginscan(rel, 0, true, NULL, 1, key);
while (HeapTupleIsValid(oldtup = systable_getnext(scan)))
{
if (pgl_heap_attisnull(oldtup, Anum_sync_nspname, NULL) &&
pgl_heap_attisnull(oldtup, Anum_sync_relname, NULL))
break;
}
if (!HeapTupleIsValid(oldtup))
elog(ERROR, "subscription %u status not found", subid);
memset(nulls, false, sizeof(nulls));
memset(replaces, false, sizeof(replaces));
values[Anum_sync_status - 1] = CharGetDatum(status);
replaces[Anum_sync_status - 1] = true;
values[Anum_sync_statuslsn - 1] = LSNGetDatum(InvalidXLogRecPtr);
replaces[Anum_sync_statuslsn - 1] = true;
newtup = heap_modify_tuple(oldtup, tupDesc, values, nulls, replaces);
/* Update the tuple in catalog. */
CatalogTupleUpdate(rel, &oldtup->t_self, newtup);
/* Cleanup. */
heap_freetuple(newtup);
systable_endscan(scan);
table_close(rel, RowExclusiveLock);
}
/* Remove table sync status record from catalog. */
void
drop_table_sync_status(const char *nspname, const char *relname)
{
RangeVar *rv;
Relation rel;
SysScanDesc scan;
HeapTuple tuple;
ScanKeyData key[2];
rv = makeRangeVar(EXTENSION_NAME, CATALOG_LOCAL_SYNC_STATUS, -1);
rel = table_openrv(rv, RowExclusiveLock);
ScanKeyInit(&key[0],
Anum_sync_nspname,
BTEqualStrategyNumber, F_NAMEEQ,
CStringGetDatum(nspname));
ScanKeyInit(&key[1],
Anum_sync_relname,
BTEqualStrategyNumber, F_NAMEEQ,
CStringGetDatum(relname));
scan = systable_beginscan(rel, 0, true, NULL, 2, key);
/* Remove the tuples. */
while (HeapTupleIsValid(tuple = systable_getnext(scan)))
simple_heap_delete(rel, &tuple->t_self);
/* Cleanup. */
systable_endscan(scan);
table_close(rel, RowExclusiveLock);
}
/* Remove table sync status record from catalog. */
void
drop_table_sync_status_for_sub(Oid subid, const char *nspname,
const char *relname)
{
RangeVar *rv;
Relation rel;
SysScanDesc scan;
HeapTuple tuple;
ScanKeyData key[3];
rv = makeRangeVar(EXTENSION_NAME, CATALOG_LOCAL_SYNC_STATUS, -1);
rel = table_openrv(rv, RowExclusiveLock);
ScanKeyInit(&key[0],
Anum_sync_subid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(subid));
ScanKeyInit(&key[1],
Anum_sync_nspname,
BTEqualStrategyNumber, F_NAMEEQ,
CStringGetDatum(nspname));
ScanKeyInit(&key[2],
Anum_sync_relname,
BTEqualStrategyNumber, F_NAMEEQ,
CStringGetDatum(relname));
scan = systable_beginscan(rel, 0, true, NULL, 3, key);
/* Remove the tuples. */
while (HeapTupleIsValid(tuple = systable_getnext(scan)))
simple_heap_delete(rel, &tuple->t_self);
/* Cleanup. */
systable_endscan(scan);
table_close(rel, RowExclusiveLock);
}
/* Get the sync status for a table. */
PGLogicalSyncStatus *
get_table_sync_status(Oid subid, const char *nspname, const char *relname,
bool missing_ok)
{
PGLogicalSyncStatus *sync;
RangeVar *rv;
Relation rel;
SysScanDesc scan;
HeapTuple tuple;
ScanKeyData key[3];
TupleDesc tupDesc;
Oid idxoid = InvalidOid;
List *indexes;
ListCell *l;
rv = makeRangeVar(EXTENSION_NAME, CATALOG_LOCAL_SYNC_STATUS, -1);
rel = table_openrv(rv, RowExclusiveLock);
/* Find an index we can use to scan this catalog. */
indexes = RelationGetIndexList(rel);
foreach (l, indexes)
{
Relation idx = index_open(lfirst_oid(l), AccessShareLock);
if (idx->rd_index->indkey.values[0] == Anum_sync_subid &&
idx->rd_index->indkey.values[1] == Anum_sync_nspname &&
idx->rd_index->indkey.values[2] == Anum_sync_relname)
{
idxoid = lfirst_oid(l);
index_close(idx, AccessShareLock);
break;
}
index_close(idx, AccessShareLock);
}
if (!OidIsValid(idxoid))
elog(ERROR, "could not find index on local_sync_status");
list_free(indexes);
tupDesc = RelationGetDescr(rel);
ScanKeyInit(&key[0],
Anum_sync_subid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(subid));
ScanKeyInit(&key[1],
Anum_sync_nspname,
BTEqualStrategyNumber, F_NAMEEQ,
CStringGetDatum(nspname));
ScanKeyInit(&key[2],
Anum_sync_relname,
BTEqualStrategyNumber, F_NAMEEQ,
CStringGetDatum(relname));
scan = systable_beginscan(rel, idxoid, true, NULL, 3, key);
tuple = systable_getnext(scan);
if (!HeapTupleIsValid(tuple))
{
if (missing_ok)
{
systable_endscan(scan);
table_close(rel, RowExclusiveLock);
return NULL;
}
elog(ERROR, "subscription %u table %s.%s status not found", subid,
nspname, relname);
}
sync = syncstatus_fromtuple(tuple, tupDesc);
systable_endscan(scan);
table_close(rel, RowExclusiveLock);
return sync;
}
/* Get the sync status for a table. */
List *
get_unsynced_tables(Oid subid)
{
PGLogicalSyncStatus *sync;
RangeVar *rv;
Relation rel;
SysScanDesc scan;
HeapTuple tuple;
ScanKeyData key[1];
List *res = NIL;
TupleDesc tupDesc;
rv = makeRangeVar(EXTENSION_NAME, CATALOG_LOCAL_SYNC_STATUS, -1);
rel = table_openrv(rv, RowExclusiveLock);
tupDesc = RelationGetDescr(rel);
ScanKeyInit(&key[0],
Anum_sync_subid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(subid));
scan = systable_beginscan(rel, 0, true, NULL, 1, key);
while (HeapTupleIsValid(tuple = systable_getnext(scan)))
{
if (pgl_heap_attisnull(tuple, Anum_sync_nspname, NULL) &&
pgl_heap_attisnull(tuple, Anum_sync_relname, NULL))
continue;
sync = syncstatus_fromtuple(tuple, tupDesc);
if (sync->status != SYNC_STATUS_READY)
res = lappend(res, sync);
}
systable_endscan(scan);
table_close(rel, RowExclusiveLock);
return res;
}
/* Get the sync status for all tables known to subscription. */
List *
get_subscription_tables(Oid subid)
{
PGLogicalSyncStatus *sync;
RangeVar *rv;
Relation rel;
SysScanDesc scan;
HeapTuple tuple;
ScanKeyData key[1];
List *res = NIL;
TupleDesc tupDesc;
rv = makeRangeVar(EXTENSION_NAME, CATALOG_LOCAL_SYNC_STATUS, -1);
rel = table_openrv(rv, RowExclusiveLock);
tupDesc = RelationGetDescr(rel);
ScanKeyInit(&key[0],
Anum_sync_subid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(subid));
scan = systable_beginscan(rel, 0, true, NULL, 1, key);
while (HeapTupleIsValid(tuple = systable_getnext(scan)))
{
if (pgl_heap_attisnull(tuple, Anum_sync_nspname, NULL) &&
pgl_heap_attisnull(tuple, Anum_sync_relname, NULL))
continue;
sync = syncstatus_fromtuple(tuple, tupDesc);
res = lappend(res, sync);
}
systable_endscan(scan);
table_close(rel, RowExclusiveLock);
return res;
}
/* Set the sync status for a table. */
void
set_table_sync_status(Oid subid, const char *nspname, const char *relname,
char status, XLogRecPtr statuslsn)
{
RangeVar *rv;
Relation rel;
TupleDesc tupDesc;
SysScanDesc scan;
HeapTuple oldtup,
newtup;
ScanKeyData key[3];
Datum values[Natts_local_sync_state];
bool nulls[Natts_local_sync_state];
bool replaces[Natts_local_sync_state];
rv = makeRangeVar(EXTENSION_NAME, CATALOG_LOCAL_SYNC_STATUS, -1);
rel = table_openrv(rv, RowExclusiveLock);
tupDesc = RelationGetDescr(rel);
ScanKeyInit(&key[0],
Anum_sync_subid,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(subid));
ScanKeyInit(&key[1],
Anum_sync_nspname,
BTEqualStrategyNumber, F_NAMEEQ,
CStringGetDatum(nspname));
ScanKeyInit(&key[2],
Anum_sync_relname,
BTEqualStrategyNumber, F_NAMEEQ,
CStringGetDatum(relname));
scan = systable_beginscan(rel, 0, true, NULL, 3, key);
oldtup = systable_getnext(scan);
if (!HeapTupleIsValid(oldtup))
elog(ERROR, "subscription %u table %s.%s status not found", subid,
nspname, relname);
memset(nulls, false, sizeof(nulls));
memset(replaces, false, sizeof(replaces));
values[Anum_sync_status - 1] = CharGetDatum(status);
replaces[Anum_sync_status - 1] = true;
values[Anum_sync_statuslsn - 1] = LSNGetDatum(statuslsn);
replaces[Anum_sync_statuslsn - 1] = true;
newtup = heap_modify_tuple(oldtup, tupDesc, values, nulls, replaces);
/* Update the tuple in catalog. */
CatalogTupleUpdate(rel, &oldtup->t_self, newtup);
/* Cleanup. */
heap_freetuple(newtup);
systable_endscan(scan);
table_close(rel, RowExclusiveLock);
}
/*
* Wait until the table sync status has changed desired one.
*
* We also exit if the worker is no longer recognized as sync worker as
* that means something bad happened to it.
*
* Care with allocations is required here since it typically runs
* in TopMemoryContext.
*/
bool
wait_for_sync_status_change(Oid subid, const char *nspname, const char *relname,
char desired_state, XLogRecPtr *lsn)
{
int rc;
MemoryContext old_ctx = CurrentMemoryContext;
bool ret = false;
*lsn = InvalidXLogRecPtr;
Assert(!IsTransactionState());
while (!got_SIGTERM)
{
PGLogicalWorker *worker;
PGLogicalSyncStatus *sync;
StartTransactionCommand();
sync = get_table_sync_status(subid, nspname, relname, true);
if (!sync)
{
CommitTransactionCommand();
break;
}
if (sync->status == desired_state)
{
*lsn = sync->statuslsn;
CommitTransactionCommand();
ret = true;
break;
}
CommitTransactionCommand();
(void) MemoryContextSwitchTo(old_ctx);
/* Check if the worker is still alive - no point waiting if it died. */
LWLockAcquire(PGLogicalCtx->lock, LW_EXCLUSIVE);
worker = pglogical_sync_find(MyDatabaseId, subid, nspname, relname);
LWLockRelease(PGLogicalCtx->lock);
if (!worker)
break;
rc = WaitLatch(&MyProc->procLatch,
WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
60000L);
ResetLatch(&MyProc->procLatch);
/* emergency bailout if postmaster has died */
if (rc & WL_POSTMASTER_DEATH)
proc_exit(1);
}
(void) MemoryContextSwitchTo(old_ctx);
return ret;
}
/*
* Truncates table if it exists.
*/
void
truncate_table(char *nspname, char *relname)
{
RangeVar *rv;
Oid relid;
TruncateStmt *truncate;
StringInfoData sql;
rv = makeRangeVar(nspname, relname, -1);
relid = RangeVarGetRelid(rv, AccessExclusiveLock, true);
if (relid == InvalidOid)
return;
initStringInfo(&sql);
appendStringInfo(&sql, "TRUNCATE TABLE %s",
quote_qualified_identifier(rv->schemaname, rv->relname));
/* Truncate the table. */
truncate = makeNode(TruncateStmt);
truncate->relations = list_make1(rv);
truncate->restart_seqs = false;
truncate->behavior = DROP_RESTRICT;
/*
* We use standard_ProcessUtility to process the truncate statement. This
* allows us to let Postgres-XL do the correct things in order to truncate
* the table from the remote nodes.
*
* Except the query string, most other parameters are made-up. This is OK
* for TruncateStmt, but if we ever decide to use standard_ProcessUtility
* for other utility statements, then we must take a careful relook.
*/
#ifdef PGXC
standard_ProcessUtility((Node *)truncate,
sql.data, PROCESS_UTILITY_TOPLEVEL, NULL, NULL,
false,
NULL
);
#else
ExecuteTruncate(truncate);
#endif
/* release memory allocated to create SQL statement */
pfree(sql.data);
CommandCounterIncrement();
}
/*
* exec_cmd support for win32
*/
#ifdef WIN32
/*
* Return formatted message from GetLastError() in a palloc'd string in the
* current memory context, or a copy of a constant generic error string if
* there's no recorded error state.
*/
static char *
PglGetLastWin32Error(void)
{
LPVOID lpMsgBuf;
DWORD dw = GetLastError();
char * pgstr = NULL;
if (dw != ERROR_SUCCESS)
{
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL);
pgstr = pstrdup((LPTSTR) lpMsgBuf);
LocalFree(lpMsgBuf);
} else {
pgstr = pstrdup("Unknown error or no recent error");
}
return pgstr;
}
/*
* See https://docs.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way
* for the utterly putrid way Windows handles command line arguments, and the insane lack of any inverse
* form of the CommandLineToArgvW function in the win32 API.
*/
static void
QuoteWindowsArgvElement(StringInfo cmdline, const char *arg, bool force)
{
if (!force && *arg != '\0'
&& strchr(arg, ' ') == NULL
&& strchr(arg, '\t') == NULL
&& strchr(arg, '\n') == NULL
&& strchr(arg, '\v') == NULL
&& strchr(arg, '"') == NULL)
{
appendStringInfoString(cmdline, arg);
}
else {
const char *it;
/* Begin quoted argument */
appendStringInfoChar(cmdline, '"');
/*
* In terms of the algorithm described in CommandLineToArgvW's
* documentation we are now "in quotes".
*/
for (it = arg; *it != '\0'; it++)
{
unsigned int NumberBackslashes = 0;
/*
* Accumulate runs of backslashes. They may or may not have special
* meaning depending on what follows them.
*/
while (*it != '\0' && *it == '\\')
{
++it;
++NumberBackslashes;
}
if (*it == '\0')
{
/*
* Handle command line arguments ending with or consisting only
* of backslashes. Particularly important for Windows, given
* its backslash paths.
*
* We want NumberBackSlashes * 2 backslashes here to prevent the
* final backslash from escaping the quote we'll append at the
* end of the argument.
*/
for (; NumberBackslashes > 0; NumberBackslashes--)
appendStringInfoString(cmdline, "\\\\");
break;
}
else if (*it == '"') {
/*
* Escape all accumulated backslashes, then append escaped
* quotation mark.
*
* We want NumberBackSlashes * 2 + 1 backslashes to prevent
* the backslashes from escaping the backslash we have to append
* to escape the quote char that's part of the argument itself.
*/
for (; NumberBackslashes > 0; NumberBackslashes--)
appendStringInfoString(cmdline, "\\\\");
appendStringInfoString(cmdline, "\\\"");
}
else {
/*
* A series of backslashes followed by something other than a
* double quote is not special to the CommandLineToArgvW parser
* in MSVCRT and must be appended literally.
*/
for (; NumberBackslashes > 0; NumberBackslashes--)
appendStringInfoChar(cmdline, '\\');
/* Finally any normal char */
appendStringInfoChar(cmdline, *it);
}
}
/* End quoted argument */
appendStringInfoChar(cmdline, '"');
/*
* In terms of the algorithm described in CommandLineToArgvW's
* documentation we are now "not in quotes".
*/
}
}
/*
* Turn an execv-style argument vector into something that Win32's
* CommandLineToArgvW will parse back into the original argument
* vector.
*
* You'd think this would be part of the win32 API. But no...
*
* (This should arguably be part of libpq_fe.c, but I didn't want to expand our
* abuse of PqExpBuffer.)
*/
static void
QuoteWindowsArgv(StringInfo cmdline, const char * argv[])
{
/* argv0 is required */
Assert(*argv != NULL && **argv != '\0');
QuoteWindowsArgvElement(cmdline, *argv, false);
++argv;
for (; *argv != NULL; ++argv)
{
appendStringInfoChar(cmdline, ' ');
QuoteWindowsArgvElement(cmdline, *argv, false);
}
}
/*
* Run a process on Windows and wait for it to exit, then return its exit code.
* Preserve argument quoting. See exec_cmd() for the function contract details.
* This is only split out to keep all the win32 horror separate for reability.
*
* Don't be tempted to use Win32's _spawnv. It is not like execv. It does *not*
* preserve the individual arguments in the vector, it concatenates them
* without any escaping or quoting. Thus any arguments with spaces, double
* quotes, etc will be mangled by the child process's MSVC runtime when it
* tries to turn the argument string back into an argument vector for the main
* function by calling CommandLineToArgv() from the C library entrypoint.
* _spawnv is also limited to 1024 characters not the 32767 characters permited
* by the underlying Win32 APIs, and that could matter for pg_dump.
*
* This provides something more like we'e expect from execv and waitpid()
* including a waitpid()-style return code with the exit code in the high
* 8 bits of a 16 bit value. Use WEXITSTATUS() for the exit status. The
* special value -1 is returned for a failure to launch the process,
* wait for it, or get its exit code.
*/
static int
exec_cmd_win32(const char *cmd, char *cmdargv[])
{
BOOL ret;
int exitcode = -1;
PROCESS_INFORMATION pi;
elog(DEBUG1, "trying to launch \"%s\"", cmd);
/* Launch the process */
{
STARTUPINFO si;
StringInfoData cmdline;
char *cmd_tmp;
/* Deal with insane windows command line quoting */
initStringInfo(&cmdline);
QuoteWindowsArgv(&cmdline, cmdargv);
/* CreateProcess may scribble on the cmd string */
cmd_tmp = pstrdup(cmd);
/*
* STARTUPINFO contains various extra options for the process that are
* not passed as CreateProcess flags, and is required.
*/
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
/*
* PROCESS_INFORMATION accepts the returned process handle.
*/
ZeroMemory( &pi, sizeof(pi) );
ret = CreateProcess(cmd_tmp, cmdline.data,
NULL /* default process attributes */,
NULL /* default thread attributes */,
TRUE /* handles (fds) are inherited, to match execv */,
CREATE_NO_WINDOW /* process creation flags */,
NULL /* inherit environment variables */,
NULL /* inherit working directory */,
&si,
&pi);
pfree(cmd_tmp);
pfree(cmdline.data);
}
if (!ret)
{
char *winerr = PglGetLastWin32Error();
ereport(LOG,
(errcode_for_file_access(),
errmsg("failed to launch \"%s\": %s",
cmd, winerr)));
pfree(winerr);
}
else
{
/*
* Process created. It can still fail due to DLL linkage errors,
* startup problems etc, but the handle exists.
*
* Wait for it to exit, while responding to interrupts. Ideally we
* should be able to use WaitEventSetWait here since Windows sees a
* process handle much like a socket, but the Pg API for it won't
* let us, so we have to DIY.
*/
elog(DEBUG1, "process launched, waiting");
do {
ret = WaitForSingleObject( pi.hProcess, 500 /* timeout in ms */ );
/*
* Note that if we elog(ERROR) or elog(FATAL) as a result of a
* signal here we won't kill the child proc.
*/
CHECK_FOR_INTERRUPTS();
if (ret == WAIT_TIMEOUT)
continue;
if (ret != WAIT_OBJECT_0)
{
char *winerr = PglGetLastWin32Error();
ereport(DEBUG1,
(errcode_for_file_access(),
errmsg("unexpected WaitForSingleObject() return code %d while waiting for child process \"%s\": %s",
ret, cmd, winerr)));
pfree(winerr);
/* Try to get the exit code anyway */
}
if (!GetExitCodeProcess( pi.hProcess, &exitcode))
{
char *winerr = PglGetLastWin32Error();
ereport(DEBUG1,
(errcode_for_file_access(),
errmsg("failed to get exit code from process \"%s\": %s",
cmd, winerr)));
pfree(winerr);
/* Give up on learning about the process's outcome */
exitcode = -1;
break;
}
else
{
/* Woken up for a reason other than child process termination */
if (exitcode == STILL_ACTIVE)
continue;
/*
* Process must've exited, so code is a value from ExitProcess,
* TerminateProcess, main or WinMain.
*/
ereport(DEBUG1,
(errmsg("process \"%s\" exited with code %d",
cmd, exitcode)));
/*
* Adapt exit code to WEXITSTATUS form to behave like waitpid().
*
* The lower 8 bits are the terminating signal, with 0 for no
* signal.
*/
exitcode = exitcode << 8;
break;
}
} while (true);
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
elog(DEBUG1, "exec_cmd_win32 for \"%s\" exiting with %d", cmd, exitcode);
return exitcode;
}
#endif
|