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
|
#include "uwsgi_python.h"
/*
This is the official python plugin, the one with the modifier1 mapped to 0
Since uWSGI 1.0 it is heavily based on Graham Dumpleton mod_wsgi (for Apache)
*/
extern struct uwsgi_server uwsgi;
struct uwsgi_python up;
#include <glob.h>
extern PyTypeObject uwsgi_InputType;
void uwsgi_opt_pythonpath(char *opt, char *value, void *foobar) {
int i;
glob_t g;
if (glob(value, GLOB_MARK, NULL, &g)) {
uwsgi_string_new_list(&up.python_path, value);
}
else {
for (i = 0; i < (int) g.gl_pathc; i++) {
uwsgi_string_new_list(&up.python_path, g.gl_pathv[i]);
}
}
}
void uwsgi_opt_pyshell(char *opt, char *value, void *foobar) {
uwsgi.honour_stdin = 1;
if (value) {
up.pyshell = value;
}
else {
up.pyshell = "";
}
if (!strcmp("pyshell-oneshot", opt)) {
up.pyshell_oneshot = 1;
}
}
void uwsgi_opt_pyrun(char *opt, char *value, void *foobar) {
uwsgi.honour_stdin = 1;
uwsgi.command_mode = 1;
up.pyrun = value;
}
void uwsgi_opt_pyver(char *opt, char *foo, void *bar) {
const char *version = Py_GetVersion();
const char *space = strchr(version, ' ');
if (space) {
fprintf(stdout, "%.*s\n", (int) (space-version), version);
}
else {
fprintf(stdout, "%s\n", version);
}
exit(0);
}
void uwsgi_opt_ini_paste(char *opt, char *value, void *foobar) {
uwsgi_opt_load_ini(opt, value, NULL);
if (value[0] != '/') {
up.paste = uwsgi_concat4("config:", uwsgi.cwd, "/", value);
}
else {
up.paste = uwsgi_concat2("config:", value);
}
if (!strcmp("ini-paste-logged", opt)) {
up.paste_logger = 1;
}
}
struct uwsgi_option uwsgi_python_options[] = {
{"wsgi-file", required_argument, 0, "load .wsgi file", uwsgi_opt_set_str, &up.file_config, 0},
{"file", required_argument, 0, "load .wsgi file", uwsgi_opt_set_str, &up.file_config, 0},
{"eval", required_argument, 0, "eval python code", uwsgi_opt_set_str, &up.eval, 0},
{"module", required_argument,'w', "load a WSGI module", uwsgi_opt_set_str, &up.wsgi_config, 0},
{"wsgi", required_argument, 'w', "load a WSGI module", uwsgi_opt_set_str, &up.wsgi_config, 0},
{"callable", required_argument, 0, "set default WSGI callable name", uwsgi_opt_set_str, &up.callable, 0},
{"test", required_argument, 'J', "test a module import", uwsgi_opt_set_str, &up.test_module, 0},
{"home", required_argument, 'H', "set PYTHONHOME/virtualenv", uwsgi_opt_set_str, &up.home, 0},
{"virtualenv", required_argument, 'H', "set PYTHONHOME/virtualenv", uwsgi_opt_set_str, &up.home, 0},
{"venv", required_argument, 'H', "set PYTHONHOME/virtualenv", uwsgi_opt_set_str, &up.home, 0},
{"pyhome", required_argument, 'H', "set PYTHONHOME/virtualenv", uwsgi_opt_set_str, &up.home, 0},
{"py-programname", required_argument, 0, "set python program name", uwsgi_opt_set_str, &up.programname, 0},
{"py-program-name", required_argument, 0, "set python program name", uwsgi_opt_set_str, &up.programname, 0},
{"pythonpath", required_argument, 0, "add directory (or glob) to pythonpath", uwsgi_opt_pythonpath, NULL, 0},
{"python-path", required_argument, 0, "add directory (or glob) to pythonpath", uwsgi_opt_pythonpath, NULL, 0},
{"pp", required_argument, 0, "add directory (or glob) to pythonpath", uwsgi_opt_pythonpath, NULL, 0},
{"pymodule-alias", required_argument, 0, "add a python alias module", uwsgi_opt_add_string_list, &up.pymodule_alias, 0},
{"post-pymodule-alias", required_argument, 0, "add a python module alias after uwsgi module initialization", uwsgi_opt_add_string_list, &up.post_pymodule_alias, 0},
{"import", required_argument, 0, "import a python module", uwsgi_opt_add_string_list, &up.import_list, 0},
{"pyimport", required_argument, 0, "import a python module", uwsgi_opt_add_string_list, &up.import_list, 0},
{"py-import", required_argument, 0, "import a python module", uwsgi_opt_add_string_list, &up.import_list, 0},
{"python-import", required_argument, 0, "import a python module", uwsgi_opt_add_string_list, &up.import_list, 0},
{"shared-import", required_argument, 0, "import a python module in all of the processes", uwsgi_opt_add_string_list, &up.shared_import_list, 0},
{"shared-pyimport", required_argument, 0, "import a python module in all of the processes", uwsgi_opt_add_string_list, &up.shared_import_list, 0},
{"shared-py-import", required_argument, 0, "import a python module in all of the processes", uwsgi_opt_add_string_list, &up.shared_import_list, 0},
{"shared-python-import", required_argument, 0, "import a python module in all of the processes", uwsgi_opt_add_string_list, &up.shared_import_list, 0},
{"spooler-import", required_argument, 0, "import a python module in the spooler", uwsgi_opt_add_string_list, &up.spooler_import_list},
{"spooler-pyimport", required_argument, 0, "import a python module in the spooler", uwsgi_opt_add_string_list, &up.spooler_import_list},
{"spooler-py-import", required_argument, 0, "import a python module in the spooler", uwsgi_opt_add_string_list, &up.spooler_import_list},
{"spooler-python-import", required_argument, 0, "import a python module in the spooler", uwsgi_opt_add_string_list, &up.spooler_import_list},
{"pyargv", required_argument, 0, "manually set sys.argv", uwsgi_opt_set_str, &up.argv, 0},
{"optimize", required_argument, 'O', "set python optimization level", uwsgi_opt_set_int, &up.optimize, 0},
{"pecan", required_argument, 0, "load a pecan config file", uwsgi_opt_set_str, &up.pecan, 0},
{"paste", required_argument, 0, "load a paste.deploy config file", uwsgi_opt_set_str, &up.paste, 0},
{"paste-logger", no_argument, 0, "enable paste fileConfig logger", uwsgi_opt_true, &up.paste_logger, 0},
{"web3", required_argument, 0, "load a web3 app", uwsgi_opt_set_str, &up.web3, 0},
{"pump", required_argument, 0, "load a pump app", uwsgi_opt_set_str, &up.pump, 0},
{"wsgi-lite", required_argument, 0, "load a wsgi-lite app", uwsgi_opt_set_str, &up.wsgi_lite, 0},
{"ini-paste", required_argument, 0, "load a paste.deploy config file containing uwsgi section", uwsgi_opt_ini_paste, NULL, UWSGI_OPT_IMMEDIATE},
{"ini-paste-logged", required_argument, 0, "load a paste.deploy config file containing uwsgi section (load loggers too)", uwsgi_opt_ini_paste, NULL, UWSGI_OPT_IMMEDIATE},
{"reload-os-env", no_argument, 0, "force reload of os.environ at each request", uwsgi_opt_true, &up.reload_os_env, 0},
#ifndef __CYGWIN__
{"no-site", no_argument, 0, "do not import site module", uwsgi_opt_true, &Py_NoSiteFlag, 0},
#endif
{"pyshell", optional_argument, 0, "run an interactive python shell in the uWSGI environment", uwsgi_opt_pyshell, NULL, 0},
{"pyshell-oneshot", optional_argument, 0, "run an interactive python shell in the uWSGI environment (one-shot variant)", uwsgi_opt_pyshell, NULL, 0},
{"python", required_argument, 0, "run a python script in the uWSGI environment", uwsgi_opt_pyrun, NULL, 0},
{"py", required_argument, 0, "run a python script in the uWSGI environment", uwsgi_opt_pyrun, NULL, 0},
{"pyrun", required_argument, 0, "run a python script in the uWSGI environment", uwsgi_opt_pyrun, NULL, 0},
{"py-tracebacker", required_argument, 0, "enable the uWSGI python tracebacker", uwsgi_opt_set_str, &up.tracebacker, UWSGI_OPT_THREADS|UWSGI_OPT_MASTER},
{"py-auto-reload", required_argument, 0, "monitor python modules mtime to trigger reload (use only in development)", uwsgi_opt_set_int, &up.auto_reload, UWSGI_OPT_THREADS|UWSGI_OPT_MASTER},
{"py-autoreload", required_argument, 0, "monitor python modules mtime to trigger reload (use only in development)", uwsgi_opt_set_int, &up.auto_reload, UWSGI_OPT_THREADS|UWSGI_OPT_MASTER},
{"python-auto-reload", required_argument, 0, "monitor python modules mtime to trigger reload (use only in development)", uwsgi_opt_set_int, &up.auto_reload, UWSGI_OPT_THREADS|UWSGI_OPT_MASTER},
{"python-autoreload", required_argument, 0, "monitor python modules mtime to trigger reload (use only in development)", uwsgi_opt_set_int, &up.auto_reload, UWSGI_OPT_THREADS|UWSGI_OPT_MASTER},
{"py-auto-reload-ignore", required_argument, 0, "ignore the specified module during auto-reload scan (can be specified multiple times)", uwsgi_opt_add_string_list, &up.auto_reload_ignore, UWSGI_OPT_THREADS|UWSGI_OPT_MASTER},
{"wsgi-env-behaviour", required_argument, 0, "set the strategy for allocating/deallocating the WSGI env", uwsgi_opt_set_str, &up.wsgi_env_behaviour, 0},
{"wsgi-env-behavior", required_argument, 0, "set the strategy for allocating/deallocating the WSGI env", uwsgi_opt_set_str, &up.wsgi_env_behaviour, 0},
{"start_response-nodelay", no_argument, 0, "send WSGI http headers as soon as possible (PEP violation)", uwsgi_opt_true, &up.start_response_nodelay, 0},
{"wsgi-strict", no_argument, 0, "try to be fully PEP compliant disabling optimizations", uwsgi_opt_true, &up.wsgi_strict, 0},
{"wsgi-accept-buffer", no_argument, 0, "accept CPython buffer-compliant objects as WSGI response in addition to string/bytes", uwsgi_opt_true, &up.wsgi_accept_buffer, 0},
{"wsgi-accept-buffers", no_argument, 0, "accept CPython buffer-compliant objects as WSGI response in addition to string/bytes", uwsgi_opt_true, &up.wsgi_accept_buffer, 0},
{"wsgi-disable-file-wrapper", no_argument, 0, "disable wsgi.file_wrapper feature", uwsgi_opt_true, &up.wsgi_disable_file_wrapper, 0},
{"python-version", no_argument, 0, "report python version", uwsgi_opt_pyver, NULL, UWSGI_OPT_IMMEDIATE},
{"python-raw", required_argument, 0, "load a python file for managing raw requests", uwsgi_opt_set_str, &up.raw, 0},
#if defined(PYTHREE) || defined(Py_TPFLAGS_HAVE_NEWBUFFER)
{"py-sharedarea", required_argument, 0, "create a sharedarea from a python bytearray object of the specified size", uwsgi_opt_add_string_list, &up.sharedarea, 0},
#endif
{"py-call-osafterfork", no_argument, 0, "enable child processes running cpython to trap OS signals", uwsgi_opt_true, &up.call_osafterfork, 0},
{"py-call-uwsgi-fork-hooks", no_argument, 0, "call pre and post hooks when uswgi forks to update the internal interpreter state of CPython", uwsgi_opt_true, &up.call_uwsgi_fork_hooks, 0},
{"python-worker-override", required_argument, 0, "override worker with the specified python script", uwsgi_opt_set_str, &up.worker_override, 0},
{"py-executable", required_argument, 0, "override sys.executable value", uwsgi_opt_set_str, &up.executable, 0},
{"py-sys-executable", required_argument, 0, "override sys.executable value", uwsgi_opt_set_str, &up.executable, 0},
{0, 0, 0, 0, 0, 0, 0},
};
/* this routine will be called after each fork to reinitialize the various locks */
void uwsgi_python_pthread_prepare(void) {
pthread_mutex_lock(&up.lock_pyloaders);
}
void uwsgi_python_pthread_parent(void) {
pthread_mutex_unlock(&up.lock_pyloaders);
}
void uwsgi_python_pthread_child(void) {
pthread_mutex_init(&up.lock_pyloaders, NULL);
}
PyMethodDef uwsgi_spit_method[] = { {"uwsgi_spit", py_uwsgi_spit, METH_VARARGS, ""} };
PyMethodDef uwsgi_write_method[] = { {"uwsgi_write", py_uwsgi_write, METH_VARARGS, ""} };
PyDoc_STRVAR(uwsgi_py_doc, "uWSGI api module.");
#ifdef PYTHREE
static PyModuleDef uwsgi_module3 = {
PyModuleDef_HEAD_INIT,
"uwsgi",
uwsgi_py_doc,
-1,
NULL,
};
PyObject *init_uwsgi3(void) {
return PyModule_Create(&uwsgi_module3);
}
#endif
int uwsgi_python_init() {
char *pyversion = strchr(Py_GetVersion(), '\n');
if (!pyversion) {
uwsgi_log_initial("Python version: %s\n", Py_GetVersion());
}
else {
uwsgi_log_initial("Python version: %.*s %s\n", pyversion-Py_GetVersion(), Py_GetVersion(), Py_GetCompiler()+1);
}
if (Py_IsInitialized()) {
uwsgi_log("--- Python VM already initialized ---\n");
PyGILState_Ensure();
goto ready;
}
if (up.home != NULL) {
if (!uwsgi_is_dir(up.home)) {
uwsgi_log("!!! Python Home is not a directory: %s !!!\n", up.home);
}
#ifdef PYTHREE
// check for PEP 405 virtualenv (starting from python 3.3)
char *pep405_env = uwsgi_concat2(up.home, "/pyvenv.cfg");
if (uwsgi_file_exists(pep405_env)) {
uwsgi_log("PEP 405 virtualenv detected: %s\n", up.home);
free(pep405_env);
goto pep405;
}
free(pep405_env);
// build the PYTHONHOME wchar path
wchar_t *wpyhome;
size_t len = strlen(up.home) + 1;
wpyhome = uwsgi_calloc(sizeof(wchar_t) * len );
if (!wpyhome) {
uwsgi_error("malloc()");
exit(1);
}
mbstowcs(wpyhome, up.home, len);
Py_SetPythonHome(wpyhome);
// do not free this memory !!!
//free(wpyhome);
pep405:
#else
Py_SetPythonHome(up.home);
#endif
uwsgi_log("Set PythonHome to %s\n", up.home);
}
char *program_name = up.programname;
if (!program_name) {
program_name = uwsgi.binary_path;
}
#ifdef PYTHREE
if (!up.programname) {
if (up.home) {
program_name = uwsgi_concat2(up.home, "/bin/python");
}
}
wchar_t *pname = uwsgi_calloc(sizeof(wchar_t) * (strlen(program_name)+1));
mbstowcs(pname, program_name, strlen(program_name)+1);
Py_SetProgramName(pname);
#ifdef UWSGI_PY312
PyImport_AppendInittab("uwsgi", init_uwsgi3);
#endif
#else
Py_SetProgramName(program_name);
#endif
Py_OptimizeFlag = up.optimize;
Py_Initialize();
ready:
if (!uwsgi.has_threads) {
uwsgi_log_initial("*** Python threads support is disabled. You can enable it with --enable-threads ***\n");
}
up.wsgi_spitout = PyCFunction_New(uwsgi_spit_method, NULL);
up.wsgi_writeout = PyCFunction_New(uwsgi_write_method, NULL);
up.main_thread = PyThreadState_Get();
// by default set a fake GIL (little impact on performance)
up.gil_get = gil_fake_get;
up.gil_release = gil_fake_release;
up.swap_ts = simple_swap_ts;
up.reset_ts = simple_reset_ts;
#if defined(PYTHREE) || defined(Py_TPFLAGS_HAVE_NEWBUFFER)
struct uwsgi_string_list *usl = NULL;
uwsgi_foreach(usl, up.sharedarea) {
uint64_t len = uwsgi_n64(usl->value);
PyObject *obj = PyByteArray_FromStringAndSize(NULL, len);
char *storage = PyByteArray_AsString(obj);
Py_INCREF(obj);
struct uwsgi_sharedarea *sa = uwsgi_sharedarea_init_ptr(storage, len);
sa->obj = obj;
}
#endif
uwsgi_log_initial("Python main interpreter initialized at %p\n", up.main_thread);
return 1;
}
void uwsgi_python_reset_random_seed() {
PyObject *random_module, *random_dict, *random_seed;
// reinitialize the random seed (thanks Jonas Borgström)
random_module = PyImport_ImportModule("random");
if (random_module) {
random_dict = PyModule_GetDict(random_module);
if (random_dict) {
random_seed = PyDict_GetItemString(random_dict, "seed");
if (random_seed) {
PyObject *random_args = PyTuple_New(1);
// pass no args
PyTuple_SetItem(random_args, 0, Py_None);
PyObject_CallObject(random_seed, random_args);
if (PyErr_Occurred()) {
PyErr_Print();
}
}
}
}
}
void uwsgi_python_atexit() {
if (uwsgi.mywid == 0) goto realstuff;
// if hijacked do not run atexit hooks
if (uwsgi.workers[uwsgi.mywid].hijacked)
return;
// if busy do not run atexit hooks
if (uwsgi_worker_is_busy(uwsgi.mywid))
return;
// managing atexit in async mode is a real pain...skip it for now
if (uwsgi.async > 1)
return;
realstuff:
// this time we use this higher level function
// as this code can be executed in a signal handler
#ifdef __GNU_kFreeBSD__
return;
#endif
if (!Py_IsInitialized()) {
return;
}
// always call it
PyGILState_Ensure();
// no need to worry about freeing memory
PyObject *uwsgi_dict = get_uwsgi_pydict("uwsgi");
if (uwsgi_dict) {
PyObject *ae = PyDict_GetItemString(uwsgi_dict, "atexit");
if (ae) {
python_call(ae, PyTuple_New(0), 0, NULL);
}
}
// this part is a 1:1 copy of mod_wsgi 3.x
// it is required to fix some atexit bug with python 3
// and to shutdown useless threads complaints
PyObject *module = PyImport_ImportModule("atexit");
Py_XDECREF(module);
if (uwsgi.has_threads) {
if (!PyImport_AddModule("dummy_threading"))
PyErr_Clear();
}
// For the reasons explained in
// https://github.com/unbit/uwsgi/issues/1384, tearing down
// the interpreter can be very expensive.
if (uwsgi.skip_atexit_teardown)
return;
Py_Finalize();
}
void uwsgi_python_post_fork() {
// Need to acquire the gil when no master process is used as first worker
// will not have been forked like others
// Necessary if uwsgi fork hooks called to update interpreter state
if (up.call_uwsgi_fork_hooks && !uwsgi.master_process && uwsgi.mywid == 1) {
UWSGI_GET_GIL
}
if (uwsgi.i_am_a_spooler) {
UWSGI_GET_GIL
}
// reset python signal flags so child processes can trap signals
// Necessary if uwsgi fork hooks not called to update interpreter state
if (!up.call_uwsgi_fork_hooks && up.call_osafterfork) {
#ifdef HAS_NOT_PYOS_FORK_STABLE_API
PyOS_AfterFork();
#else
PyOS_AfterFork_Child();
#endif
}
uwsgi_python_reset_random_seed();
// call the post_fork_hook
PyObject *uwsgi_dict = get_uwsgi_pydict("uwsgi");
if (uwsgi_dict) {
PyObject *pfh = PyDict_GetItemString(uwsgi_dict, "post_fork_hook");
if (pfh) {
python_call(pfh, PyTuple_New(0), 0, NULL);
}
}
PyErr_Clear();
if (uwsgi.mywid > 0) {
uwsgi_python_set_thread_name(0);
if (up.auto_reload) {
// spawn the reloader thread
pthread_t par_tid;
pthread_create(&par_tid, NULL, uwsgi_python_autoreloader_thread, NULL);
}
if (up.tracebacker) {
// spawn the tracebacker thread
pthread_t ptb_tid;
pthread_create(&ptb_tid, NULL, uwsgi_python_tracebacker_thread, NULL);
}
}
UWSGI_RELEASE_GIL
}
PyObject *uwsgi_pyimport_by_filename(char *name, char *filename) {
char *pycontent;
PyObject *py_compiled_node, *py_file_module;
int is_a_package = 0;
struct stat pystat;
char *real_filename = filename;
if (!uwsgi_check_scheme(filename)) {
FILE *pyfile = fopen(filename, "r");
if (!pyfile) {
uwsgi_log("failed to open python file %s\n", filename);
return NULL;
}
if (fstat(fileno(pyfile), &pystat)) {
fclose(pyfile);
uwsgi_error("fstat()");
return NULL;
}
if (S_ISDIR(pystat.st_mode)) {
is_a_package = 1;
fclose(pyfile);
real_filename = uwsgi_concat2(filename, "/__init__.py");
pyfile = fopen(real_filename, "r");
if (!pyfile) {
uwsgi_error_open(real_filename);
free(real_filename);
return NULL;
}
}
fclose(pyfile);
pycontent = uwsgi_simple_file_read(real_filename);
if (!pycontent) {
if (is_a_package) {
free(real_filename);
}
uwsgi_log("no data read from file %s\n", real_filename);
return NULL;
}
}
else {
size_t pycontent_size = 0;
pycontent = uwsgi_open_and_read(filename, &pycontent_size, 1, NULL);
if (!pycontent) {
uwsgi_log("no data read from url %s\n", real_filename);
return NULL;
}
}
py_compiled_node = Py_CompileString(pycontent, real_filename, Py_file_input);
if (!py_compiled_node) {
PyErr_Print();
uwsgi_log("failed to compile %s\n", real_filename);
return NULL;
}
if (is_a_package) {
py_file_module = PyImport_AddModule(name);
if (py_file_module) {
PyModule_AddObject(py_file_module, "__path__", Py_BuildValue("[O]", PyString_FromString(filename)));
}
free(real_filename);
}
py_file_module = PyImport_ExecCodeModule(name, py_compiled_node);
if (!py_file_module) {
PyErr_Print();
return NULL;
}
Py_DECREF(py_compiled_node);
return py_file_module;
}
void init_uwsgi_vars() {
PyObject *pysys, *pysys_dict, *pypath;
PyObject *modules = PyImport_GetModuleDict();
PyObject *tmp_module;
/* add cwd to pythonpath */
pysys = PyImport_ImportModule("sys");
if (!pysys) {
PyErr_Print();
exit(1);
}
pysys_dict = PyModule_GetDict(pysys);
#ifdef PYTHREE
// In python3, stdout / stderr was changed to be buffered (a bug according
// to many):
// - https://bugs.python.org/issue13597
// - https://bugs.python.org/issue13601
// We'll fix this by manually restore the unbuffered behaviour.
// In the case of a tty, this fix breaks readline support in interactive
// debuggers so we'll only do this in the non-tty case.
if (!Py_FdIsInteractive(stdin, NULL)) {
#ifdef HAS_NO_ERRORS_IN_PyFile_FromFd
PyObject *new_stdprint = PyFile_FromFd(2, NULL, "w", _IOLBF, NULL, NULL, 0);
#else
PyObject *new_stdprint = PyFile_FromFd(2, NULL, "w", _IOLBF, NULL, "backslashreplace", NULL, 0);
#endif
PyDict_SetItemString(pysys_dict, "stdout", new_stdprint);
PyDict_SetItemString(pysys_dict, "__stdout__", new_stdprint);
PyDict_SetItemString(pysys_dict, "stderr", new_stdprint);
PyDict_SetItemString(pysys_dict, "__stderr__", new_stdprint);
}
#endif
pypath = PyDict_GetItemString(pysys_dict, "path");
if (!pypath) {
PyErr_Print();
exit(1);
}
if (PyList_Insert(pypath, 0, UWSGI_PYFROMSTRING(".")) != 0) {
PyErr_Print();
}
struct uwsgi_string_list *uppp = up.python_path;
while(uppp) {
if (PyList_Insert(pypath, 0, UWSGI_PYFROMSTRING(uppp->value)) != 0) {
PyErr_Print();
}
else {
uwsgi_log("added %s to pythonpath.\n", uppp->value);
}
uppp = uppp->next;
}
struct uwsgi_string_list *uppma = up.pymodule_alias;
while(uppma) {
// split key=value
char *value = strchr(uppma->value, '=');
if (!value) {
uwsgi_log("invalid pymodule-alias syntax\n");
goto next;
}
value[0] = 0;
if (!strchr(value + 1, '/')) {
// this is a standard pymodule
tmp_module = PyImport_ImportModule(value + 1);
if (!tmp_module) {
PyErr_Print();
exit(1);
}
PyDict_SetItemString(modules, uppma->value, tmp_module);
}
else {
// this is a filepath that need to be mapped
tmp_module = uwsgi_pyimport_by_filename(uppma->value, value + 1);
if (!tmp_module) {
PyErr_Print();
exit(1);
}
}
uwsgi_log("mapped virtual pymodule \"%s\" to real pymodule \"%s\"\n", uppma->value, value + 1);
// reset original value
value[0] = '=';
next:
uppma = uppma->next;
}
}
void init_uwsgi_embedded_module() {
PyObject *new_uwsgi_module, *zero;
int i;
if (PyType_Ready(&uwsgi_InputType) < 0) {
PyErr_Print();
uwsgi_log("could not initialize the uwsgi python module\n");
exit(1);
}
/* initialize for stats */
up.workers_tuple = PyTuple_New(uwsgi.numproc);
for (i = 0; i < uwsgi.numproc; i++) {
zero = PyDict_New();
Py_INCREF(zero);
PyTuple_SetItem(up.workers_tuple, i, zero);
}
#ifdef PYTHREE
#ifndef UWSGI_PY312
PyImport_AppendInittab("uwsgi", init_uwsgi3);
#endif
new_uwsgi_module = PyImport_AddModule("uwsgi");
#else
new_uwsgi_module = Py_InitModule3("uwsgi", NULL, uwsgi_py_doc);
#endif
if (new_uwsgi_module == NULL) {
uwsgi_log("could not initialize the uwsgi python module\n");
exit(1);
}
Py_INCREF((PyObject *) &uwsgi_InputType);
up.embedded_dict = PyModule_GetDict(new_uwsgi_module);
if (!up.embedded_dict) {
uwsgi_log("could not get uwsgi module __dict__\n");
exit(1);
}
// just for safety
Py_INCREF(up.embedded_dict);
if (PyDict_SetItemString(up.embedded_dict, "version", PyString_FromString(UWSGI_VERSION))) {
PyErr_Print();
exit(1);
}
PyObject *uwsgi_py_version_info = PyTuple_New(5);
PyTuple_SetItem(uwsgi_py_version_info, 0, PyInt_FromLong(UWSGI_VERSION_BASE));
PyTuple_SetItem(uwsgi_py_version_info, 1, PyInt_FromLong(UWSGI_VERSION_MAJOR));
PyTuple_SetItem(uwsgi_py_version_info, 2, PyInt_FromLong(UWSGI_VERSION_MINOR));
PyTuple_SetItem(uwsgi_py_version_info, 3, PyInt_FromLong(UWSGI_VERSION_REVISION));
PyTuple_SetItem(uwsgi_py_version_info, 4, PyString_FromString(UWSGI_VERSION_CUSTOM));
if (PyDict_SetItemString(up.embedded_dict, "version_info", uwsgi_py_version_info)) {
PyErr_Print();
exit(1);
}
if (PyDict_SetItemString(up.embedded_dict, "hostname", PyString_FromStringAndSize(uwsgi.hostname, uwsgi.hostname_len))) {
PyErr_Print();
exit(1);
}
if (uwsgi.mode) {
if (PyDict_SetItemString(up.embedded_dict, "mode", PyString_FromString(uwsgi.mode))) {
PyErr_Print();
exit(1);
}
}
if (uwsgi.pidfile) {
if (PyDict_SetItemString(up.embedded_dict, "pidfile", PyString_FromString(uwsgi.pidfile))) {
PyErr_Print();
exit(1);
}
}
if (uwsgi.spoolers) {
int sc = 0;
struct uwsgi_spooler *uspool = uwsgi.spoolers;
while(uspool) { sc++; uspool = uspool->next;}
PyObject *py_spooler_tuple = PyTuple_New(sc);
uspool = uwsgi.spoolers;
sc = 0;
while(uspool) {
PyTuple_SetItem(py_spooler_tuple, sc, PyString_FromString(uspool->dir));
sc++;
uspool = uspool->next;
}
if (PyDict_SetItemString(up.embedded_dict, "spoolers", py_spooler_tuple)) {
PyErr_Print();
exit(1);
}
}
if (PyDict_SetItemString(up.embedded_dict, "SPOOL_RETRY", PyInt_FromLong(-1))) {
PyErr_Print();
exit(1);
}
if (PyDict_SetItemString(up.embedded_dict, "SPOOL_OK", PyInt_FromLong(-2))) {
PyErr_Print();
exit(1);
}
if (PyDict_SetItemString(up.embedded_dict, "SPOOL_IGNORE", PyInt_FromLong(0))) {
PyErr_Print();
exit(1);
}
if (PyDict_SetItemString(up.embedded_dict, "numproc", PyInt_FromLong(uwsgi.numproc))) {
PyErr_Print();
exit(1);
}
if (PyDict_SetItemString(up.embedded_dict, "has_threads", PyInt_FromLong(uwsgi.has_threads))) {
PyErr_Print();
exit(1);
}
if (PyDict_SetItemString(up.embedded_dict, "cores", PyInt_FromLong(uwsgi.cores))) {
PyErr_Print();
exit(1);
}
if (uwsgi.loop) {
if (PyDict_SetItemString(up.embedded_dict, "loop", PyString_FromString(uwsgi.loop))) {
PyErr_Print();
exit(1);
}
}
else {
PyDict_SetItemString(up.embedded_dict, "loop", Py_None);
}
PyObject *py_opt_dict = PyDict_New();
for (i = 0; i < uwsgi.exported_opts_cnt; i++) {
if (PyDict_Contains(py_opt_dict, PyString_FromString(uwsgi.exported_opts[i]->key))) {
PyObject *py_opt_item = PyDict_GetItemString(py_opt_dict, uwsgi.exported_opts[i]->key);
if (PyList_Check(py_opt_item)) {
if (uwsgi.exported_opts[i]->value == NULL) {
PyList_Append(py_opt_item, Py_True);
}
else {
PyList_Append(py_opt_item, PyString_FromString(uwsgi.exported_opts[i]->value));
}
}
else {
PyObject *py_opt_list = PyList_New(0);
PyList_Append(py_opt_list, py_opt_item);
if (uwsgi.exported_opts[i]->value == NULL) {
PyList_Append(py_opt_list, Py_True);
}
else {
PyList_Append(py_opt_list, PyString_FromString(uwsgi.exported_opts[i]->value));
}
PyDict_SetItemString(py_opt_dict, uwsgi.exported_opts[i]->key, py_opt_list);
}
}
else {
if (uwsgi.exported_opts[i]->value == NULL) {
PyDict_SetItemString(py_opt_dict, uwsgi.exported_opts[i]->key, Py_True);
}
else {
PyDict_SetItemString(py_opt_dict, uwsgi.exported_opts[i]->key, PyString_FromString(uwsgi.exported_opts[i]->value));
}
}
}
if (PyDict_SetItemString(up.embedded_dict, "opt", py_opt_dict)) {
PyErr_Print();
exit(1);
}
PyObject *py_sockets_list = PyList_New(0);
struct uwsgi_socket *uwsgi_sock = uwsgi.sockets;
while(uwsgi_sock) {
if (uwsgi_sock->bound) {
PyList_Append(py_sockets_list, PyInt_FromLong(uwsgi_sock->fd));
}
uwsgi_sock = uwsgi_sock->next;
}
if (PyDict_SetItemString(up.embedded_dict, "sockets", py_sockets_list)) {
PyErr_Print();
exit(1);
}
PyObject *py_magic_table = PyDict_New();
uint8_t mtk;
for (i = 0; i <= 0xff; i++) {
// a bit of magic :P
mtk = i;
if (uwsgi.magic_table[i]) {
if (uwsgi.magic_table[i][0] != 0) {
PyDict_SetItem(py_magic_table, PyString_FromStringAndSize((char *) &mtk, 1), PyString_FromString(uwsgi.magic_table[i]));
}
}
}
if (PyDict_SetItemString(up.embedded_dict, "magic_table", py_magic_table)) {
PyErr_Print();
exit(1);
}
#ifdef UNBIT
if (PyDict_SetItemString(up.embedded_dict, "unbit", Py_True)) {
#else
if (PyDict_SetItemString(up.embedded_dict, "unbit", Py_None)) {
#endif
PyErr_Print();
exit(1);
}
if (PyDict_SetItemString(up.embedded_dict, "buffer_size", PyInt_FromLong(uwsgi.buffer_size))) {
PyErr_Print();
exit(1);
}
if (PyDict_SetItemString(up.embedded_dict, "started_on", PyInt_FromLong(uwsgi.start_tv.tv_sec))) {
PyErr_Print();
exit(1);
}
if (PyDict_SetItemString(up.embedded_dict, "start_response", up.wsgi_spitout)) {
PyErr_Print();
exit(1);
}
if (PyDict_SetItemString(up.embedded_dict, "applications", Py_None)) {
PyErr_Print();
exit(1);
}
if (uwsgi.is_a_reload) {
if (PyDict_SetItemString(up.embedded_dict, "is_a_reload", Py_True)) {
PyErr_Print();
exit(1);
}
}
else {
if (PyDict_SetItemString(up.embedded_dict, "is_a_reload", Py_False)) {
PyErr_Print();
exit(1);
}
}
init_uwsgi_module_advanced(new_uwsgi_module);
if (uwsgi.spoolers) {
init_uwsgi_module_spooler(new_uwsgi_module);
}
if (uwsgi.sharedareas) {
init_uwsgi_module_sharedarea(new_uwsgi_module);
}
init_uwsgi_module_cache(new_uwsgi_module);
if (uwsgi.queue_size > 0) {
init_uwsgi_module_queue(new_uwsgi_module);
}
if (uwsgi.snmp) {
init_uwsgi_module_snmp(new_uwsgi_module);
}
if (up.extension) {
up.extension();
}
}
int uwsgi_python_magic(char *mountpoint, char *lazy) {
char *qc = strchr(lazy, ':');
if (qc) {
qc[0] = 0;
up.callable = qc + 1;
}
if (!strcmp(lazy + strlen(lazy) - 3, ".py")) {
up.file_config = lazy;
return 1;
}
else if (!strcmp(lazy + strlen(lazy) - 5, ".wsgi")) {
up.file_config = lazy;
return 1;
}
else if (qc && strchr(lazy, '.')) {
up.wsgi_config = lazy;
return 1;
}
// reset lazy
if (qc) {
qc[0] = ':';
}
return 0;
}
int uwsgi_python_mount_app(char *mountpoint, char *app) {
int id;
if (strchr(app, ':') || uwsgi_endswith(app, ".py") || uwsgi_endswith(app, ".wsgi")) {
uwsgi.wsgi_req->appid = mountpoint;
uwsgi.wsgi_req->appid_len = strlen(mountpoint);
// lazy ?
if (uwsgi.mywid > 0) UWSGI_GET_GIL
if (uwsgi.single_interpreter) {
id = init_uwsgi_app(LOADER_MOUNT, app, uwsgi.wsgi_req, up.main_thread, PYTHON_APP_TYPE_WSGI);
}
else {
id = init_uwsgi_app(LOADER_MOUNT, app, uwsgi.wsgi_req, NULL, PYTHON_APP_TYPE_WSGI);
}
// lazy ?
if (uwsgi.mywid > 0) UWSGI_RELEASE_GIL
return id;
}
return -1;
}
char *uwsgi_pythonize(char *orig) {
char *name;
size_t i, len, offset = 0;
if (!strncmp(orig, "sym://", 6)) {
offset = 6;
}
else if (!strncmp(orig, "http://", 7)) {
offset = 7;
}
else if (!strncmp(orig, "data://", 7)) {
offset = 7;
}
name = uwsgi_concat2(orig+offset, "");
len = strlen(name);
for(i=0;i<len;i++) {
if (name[i] == '.') {
name[i] = '_';
}
else if (name[i] == '/') {
name[i] = '_';
}
}
if ((name[len-3] == '.' || name[len-3] == '_') && name[len-2] == 'p' && name[len-1] == 'y') {
name[len-3] = 0;
}
return name;
}
void uwsgi_python_spooler_init(void) {
struct uwsgi_string_list *upli = up.spooler_import_list;
UWSGI_GET_GIL
while(upli) {
if (strchr(upli->value, '/') || uwsgi_endswith(upli->value, ".py")) {
uwsgi_pyimport_by_filename(uwsgi_pythonize(upli->value), upli->value);
}
else {
if (PyImport_ImportModule(upli->value) == NULL) {
PyErr_Print();
}
}
upli = upli->next;
}
UWSGI_RELEASE_GIL
}
// this is the default (fake) allocator for WSGI's env
// the dictionary is created on app loading (one for each async core/thread) and reused (clearing it after each request, constantly)
//
// from a python-programmer point of view it is a hack/cheat but it does not violate the WSGI standard
// and it is a bit faster than the "holy" allocator
void *uwsgi_python_create_env_cheat(struct wsgi_request *wsgi_req, struct uwsgi_app *wi) {
wsgi_req->async_args = wi->args[wsgi_req->async_id];
Py_INCREF((PyObject *)wi->environ[wsgi_req->async_id]);
return wi->environ[wsgi_req->async_id];
}
void uwsgi_python_destroy_env_cheat(struct wsgi_request *wsgi_req) {
PyDict_Clear((PyObject *)wsgi_req->async_environ);
}
// this is the "holy" allocator for WSGI's env
// Armin Ronacher told me this is what most of python programmers expect
// I cannot speak for that as i am a perl guy, and i expect only black-magic things :P
//
// this should be the default one, but changing default behaviours (even if they are wrong)
// always make my customers going berserk...
//
// it is only slightly (better: irrelevant) slower, so no fear in enabling it...
void *uwsgi_python_create_env_holy(struct wsgi_request *wsgi_req, struct uwsgi_app *wi) {
wsgi_req->async_args = PyTuple_New(2);
// set start_response()
Py_INCREF(Py_None);
Py_INCREF(up.wsgi_spitout);
PyTuple_SetItem((PyObject *)wsgi_req->async_args, 0, Py_None);
PyTuple_SetItem((PyObject *)wsgi_req->async_args, 1, up.wsgi_spitout);
PyObject *env = PyDict_New();
return env;
}
void uwsgi_python_destroy_env_holy(struct wsgi_request *wsgi_req) {
if (uwsgi.threads < 2) {
// in non-multithread modes, we set uwsgi.env, so let's remove it now
// to equalise the refcount of the environ
PyDict_DelItemString(up.embedded_dict, "env");
}
// avoid to decref environ if it is mapped to the python callable
if (PyTuple_GetItem(wsgi_req->async_args, 0) != wsgi_req->async_environ) {
Py_DECREF((PyObject *)wsgi_req->async_environ);
}
Py_DECREF((PyObject *) wsgi_req->async_args);
}
// this hook will be executed by master (or worker1 when master is not requested, so COW is in place)
void uwsgi_python_preinit_apps() {
// GIL was released in previous initialization steps but init_pyargv expects
// the GIL to be acquired
// Necessary if uwsgi fork hooks called to update interpreter state
if (up.call_uwsgi_fork_hooks) {
UWSGI_GET_GIL
}
init_pyargv();
init_uwsgi_embedded_module();
#ifdef __linux__
uwsgi_init_symbol_import();
#endif
if (up.test_module != NULL) {
if (PyImport_ImportModule(up.test_module)) {
exit(0);
}
exit(1);
}
if (up.wsgi_env_behaviour) {
if (!strcmp(up.wsgi_env_behaviour, "holy")) {
up.wsgi_env_create = uwsgi_python_create_env_holy;
up.wsgi_env_destroy = uwsgi_python_destroy_env_holy;
}
else if (!strcmp(up.wsgi_env_behaviour, "cheat")) {
up.wsgi_env_create = uwsgi_python_create_env_cheat;
up.wsgi_env_destroy = uwsgi_python_destroy_env_cheat;
}
else {
uwsgi_log("invalid wsgi-env-behaviour value: %s\n", up.wsgi_env_behaviour);
exit(1);
}
}
else {
up.wsgi_env_create = uwsgi_python_create_env_cheat;
up.wsgi_env_destroy = uwsgi_python_destroy_env_cheat;
}
init_uwsgi_vars();
// load shared imports
struct uwsgi_string_list *upli = up.shared_import_list;
while(upli) {
if (strchr(upli->value, '/') || uwsgi_endswith(upli->value, ".py")) {
uwsgi_pyimport_by_filename(uwsgi_pythonize(upli->value), upli->value);
}
else {
if (PyImport_ImportModule(upli->value) == NULL) {
PyErr_Print();
}
}
upli = upli->next;
}
// Release the GIL before moving on forward with initialization
// Necessary if uwsgi fork hooks called to update interpreter state
if (up.call_uwsgi_fork_hooks) {
UWSGI_RELEASE_GIL
}
}
void uwsgi_python_init_apps() {
// lazy ?
// Also necessary if uwsgi fork hooks called to update interpreter state
if (uwsgi.mywid > 0 || up.call_uwsgi_fork_hooks) {
UWSGI_GET_GIL;
}
// prepare for stack suspend/resume
if (uwsgi.async > 1) {
#ifdef UWSGI_PY314
up.current_py_recursion_remaining = uwsgi_malloc(sizeof(int)*uwsgi.async);
#elif defined UWSGI_PY312
up.current_c_recursion_remaining = uwsgi_malloc(sizeof(int)*uwsgi.async);
up.current_py_recursion_remaining = uwsgi_malloc(sizeof(int)*uwsgi.async);
#elif defined UWSGI_PY311
up.current_recursion_remaining = uwsgi_malloc(sizeof(int)*uwsgi.async);
#else
up.current_recursion_depth = uwsgi_malloc(sizeof(int)*uwsgi.async);
#endif
up.current_frame = uwsgi_malloc(sizeof(up.current_frame[0])*uwsgi.async);
}
// setup app loaders
up.loaders[LOADER_DYN] = uwsgi_dyn_loader;
up.loaders[LOADER_UWSGI] = uwsgi_uwsgi_loader;
up.loaders[LOADER_FILE] = uwsgi_file_loader;
up.loaders[LOADER_PECAN] = uwsgi_pecan_loader;
up.loaders[LOADER_PASTE] = uwsgi_paste_loader;
up.loaders[LOADER_EVAL] = uwsgi_eval_loader;
up.loaders[LOADER_MOUNT] = uwsgi_mount_loader;
up.loaders[LOADER_CALLABLE] = uwsgi_callable_loader;
up.loaders[LOADER_STRING_CALLABLE] = uwsgi_string_callable_loader;
struct uwsgi_string_list *upli = up.import_list;
while(upli) {
if (strchr(upli->value, '/') || uwsgi_endswith(upli->value, ".py")) {
uwsgi_pyimport_by_filename(uwsgi_pythonize(upli->value), upli->value);
}
else {
if (PyImport_ImportModule(upli->value) == NULL) {
PyErr_Print();
}
}
upli = upli->next;
}
struct uwsgi_string_list *uppa = up.post_pymodule_alias;
PyObject *modules = PyImport_GetModuleDict();
PyObject *tmp_module;
while(uppa) {
// split key=value
char *value = strchr(uppa->value, '=');
if (!value) {
uwsgi_log("invalid pymodule-alias syntax\n");
goto next;
}
value[0] = 0;
if (!strchr(value + 1, '/')) {
// this is a standard pymodule
tmp_module = PyImport_ImportModule(value + 1);
if (!tmp_module) {
PyErr_Print();
exit(1);
}
PyDict_SetItemString(modules, uppa->value, tmp_module);
}
else {
// this is a filepath that need to be mapped
tmp_module = uwsgi_pyimport_by_filename(uppa->value, value + 1);
if (!tmp_module) {
PyErr_Print();
exit(1);
}
}
uwsgi_log("mapped virtual pymodule \"%s\" to real pymodule \"%s\"\n", uppa->value, value + 1);
// reset original value
value[0] = '=';
next:
uppa = uppa->next;
}
if (up.raw) {
up.raw_callable = uwsgi_file_loader(up.raw);
if (up.raw_callable) {
Py_INCREF(up.raw_callable);
}
}
if (up.wsgi_config != NULL) {
init_uwsgi_app(LOADER_UWSGI, up.wsgi_config, uwsgi.wsgi_req, up.main_thread, PYTHON_APP_TYPE_WSGI);
}
if (up.file_config != NULL) {
init_uwsgi_app(LOADER_FILE, up.file_config, uwsgi.wsgi_req, up.main_thread, PYTHON_APP_TYPE_WSGI);
}
if (up.pecan != NULL) {
init_uwsgi_app(LOADER_PECAN, up.pecan, uwsgi.wsgi_req, up.main_thread, PYTHON_APP_TYPE_WSGI);
}
if (up.paste != NULL) {
init_uwsgi_app(LOADER_PASTE, up.paste, uwsgi.wsgi_req, up.main_thread, PYTHON_APP_TYPE_WSGI);
}
if (up.eval != NULL) {
init_uwsgi_app(LOADER_EVAL, up.eval, uwsgi.wsgi_req, up.main_thread, PYTHON_APP_TYPE_WSGI);
}
if (up.web3 != NULL) {
init_uwsgi_app(LOADER_UWSGI, up.web3, uwsgi.wsgi_req, up.main_thread, PYTHON_APP_TYPE_WEB3);
}
if (up.pump != NULL) {
init_uwsgi_app(LOADER_UWSGI, up.pump, uwsgi.wsgi_req, up.main_thread, PYTHON_APP_TYPE_PUMP);
}
if (up.wsgi_lite != NULL) {
init_uwsgi_app(LOADER_UWSGI, up.wsgi_lite, uwsgi.wsgi_req, up.main_thread, PYTHON_APP_TYPE_WSGI_LITE);
}
if (uwsgi.profiler) {
if (!strcmp(uwsgi.profiler, "pycall")) {
PyEval_SetProfile(uwsgi_python_profiler_call, NULL);
}
else if (!strcmp(uwsgi.profiler, "pyline")) {
PyEval_SetTrace(uwsgi_python_tracer, NULL);
}
}
PyObject *uwsgi_dict = get_uwsgi_pydict("uwsgi");
if (uwsgi_dict) {
up.after_req_hook = PyDict_GetItemString(uwsgi_dict, "after_req_hook");
if (up.after_req_hook) {
Py_INCREF(up.after_req_hook);
up.after_req_hook_args = PyTuple_New(0);
Py_INCREF(up.after_req_hook_args);
}
}
// lazy ?
// Also necessary if uwsgi fork hooks called to update interpreter state
if (uwsgi.mywid > 0 || up.call_uwsgi_fork_hooks) {
UWSGI_RELEASE_GIL;
}
}
void uwsgi_python_master_fixup(int step) {
static int master_fixed = 0;
static int worker_fixed = 0;
if (!uwsgi.master_process) return;
// Skip master fixup if uwsgi fork hooks called to update interpreter state
if (up.call_uwsgi_fork_hooks)
return;
if (uwsgi.has_threads) {
if (step == 0) {
if (!master_fixed) {
UWSGI_RELEASE_GIL;
master_fixed = 1;
}
}
else {
if (!worker_fixed) {
UWSGI_GET_GIL;
worker_fixed = 1;
}
}
}
}
void uwsgi_python_pre_uwsgi_fork() {
if (!up.call_uwsgi_fork_hooks)
return;
if (uwsgi.has_threads) {
// Acquire the gil and import lock before forking in order to avoid
// deadlocks in workers
UWSGI_GET_GIL
#ifdef HAS_NOT_PYOS_FORK_STABLE_API
_PyImport_AcquireLock();
#else
PyOS_BeforeFork();
#endif
}
}
void uwsgi_python_post_uwsgi_fork(int step) {
if (!up.call_uwsgi_fork_hooks)
return;
if (uwsgi.has_threads) {
if (step == 0) {
// Release locks within master process
#ifdef HAS_NOT_PYOS_FORK_STABLE_API
_PyImport_ReleaseLock();
#else
PyOS_AfterFork_Parent();
#endif
UWSGI_RELEASE_GIL
}
else {
// Ensure thread state and locks are cleaned up in child process
#ifdef HAS_NOT_PYOS_FORK_STABLE_API
PyOS_AfterFork();
#else
PyOS_AfterFork_Child();
#endif
}
}
}
void uwsgi_python_enable_threads() {
#ifdef UWSGI_SHOULD_CALL_PYEVAL_INITTHREADS
PyEval_InitThreads();
#endif
if (pthread_key_create(&up.upt_save_key, NULL)) {
uwsgi_error("pthread_key_create()");
exit(1);
}
if (pthread_key_create(&up.upt_gil_key, NULL)) {
uwsgi_error("pthread_key_create()");
exit(1);
}
pthread_setspecific(up.upt_save_key, (void *) PyThreadState_Get());
pthread_setspecific(up.upt_gil_key, (void *) PyThreadState_Get());
pthread_mutex_init(&up.lock_pyloaders, NULL);
pthread_atfork(uwsgi_python_pthread_prepare, uwsgi_python_pthread_parent, uwsgi_python_pthread_child);
up.gil_get = gil_real_get;
up.gil_release = gil_real_release;
up.swap_ts = simple_threaded_swap_ts;
up.reset_ts = simple_threaded_reset_ts;
if (uwsgi.threads > 1) {
up.swap_ts = threaded_swap_ts;
up.reset_ts = threaded_reset_ts;
}
// Release the newly created gil from call to PyEval_InitThreads above
// Necessary if uwsgi fork hooks called to update interpreter state
if (up.call_uwsgi_fork_hooks) {
UWSGI_RELEASE_GIL
}
uwsgi_log("python threads support enabled\n");
}
void uwsgi_python_set_thread_name(int core_id) {
// call threading.current_thread (taken from mod_wsgi, but removes DECREFs as thread in uWSGI are fixed)
PyObject *threading_module = PyImport_ImportModule("threading");
if (threading_module) {
PyObject *threading_module_dict = PyModule_GetDict(threading_module);
if (threading_module_dict) {
PyObject *threading_current = PyDict_GetItemString(threading_module_dict, "current_thread");
if (threading_current) {
PyObject *current_thread = PyObject_CallObject(threading_current, (PyObject *)NULL);
if (!current_thread) {
// ignore the error
PyErr_Clear();
}
else {
#ifdef PYTHREE
PyObject_SetAttrString(current_thread, "name", PyUnicode_FromFormat("uWSGIWorker%dCore%d", uwsgi.mywid, core_id));
#else
PyObject_SetAttrString(current_thread, "name", PyString_FromFormat("uWSGIWorker%dCore%d", uwsgi.mywid, core_id));
#endif
Py_INCREF(current_thread);
}
}
}
}
}
void uwsgi_python_init_thread(int core_id) {
// set a new ThreadState for each thread
PyThreadState *pts;
pts = PyThreadState_New(up.main_thread->interp);
pthread_setspecific(up.upt_save_key, (void *) pts);
pthread_setspecific(up.upt_gil_key, (void *) pts);
#ifdef UWSGI_DEBUG
uwsgi_log("python ThreadState %d = %p\n", core_id, pts);
#endif
UWSGI_GET_GIL;
uwsgi_python_set_thread_name(core_id);
UWSGI_RELEASE_GIL;
}
int uwsgi_check_python_mtime(PyObject *times_dict, char *filename) {
struct stat st;
PyObject *py_mtime = PyDict_GetItemString(times_dict, filename);
if (!py_mtime) {
if (stat(filename, &st)) {
return 0;
}
PyDict_SetItemString(times_dict, filename, PyLong_FromLong(st.st_mtime));
}
// the record is already tracked;
else {
long mtime = PyLong_AsLong(py_mtime);
if (stat(filename, &st)) {
return 0;
}
if ((long) st.st_mtime != mtime) {
uwsgi_log("[uwsgi-python-reloader] module/file %s has been modified\n", filename);
kill(uwsgi.workers[0].pid, SIGHUP);
return 1;
}
}
return 0;
}
PyObject *uwsgi_python_setup_thread(char *name) {
// block signals on this thread
sigset_t smask;
sigfillset(&smask);
#ifndef UWSGI_DEBUG
sigdelset(&smask, SIGSEGV);
#endif
pthread_sigmask(SIG_BLOCK, &smask, NULL);
PyThreadState *pts = PyThreadState_New(up.main_thread->interp);
pthread_setspecific(up.upt_save_key, (void *) pts);
pthread_setspecific(up.upt_gil_key, (void *) pts);
UWSGI_GET_GIL;
PyObject *threading_module = PyImport_ImportModule("threading");
if (threading_module) {
PyObject *threading_module_dict = PyModule_GetDict(threading_module);
if (threading_module_dict) {
PyObject *threading_current = PyDict_GetItemString(threading_module_dict, "current_thread");
if (threading_current) {
PyObject *current_thread = PyObject_CallObject(threading_current, (PyObject *)NULL);
if (!current_thread) {
// ignore the error
PyErr_Clear();
}
else {
PyObject_SetAttrString(current_thread, "name", PyString_FromString(name));
Py_INCREF(current_thread);
return current_thread;
}
}
}
}
return NULL;
}
void *uwsgi_python_autoreloader_thread(void *foobar) {
PyObject *new_thread = uwsgi_python_setup_thread("uWSGIAutoReloader");
if (!new_thread) return NULL;
PyObject *modules = PyImport_GetModuleDict();
if (uwsgi.mywid == 1) {
uwsgi_log("Python auto-reloader enabled\n");
}
PyObject *times_dict = PyDict_New();
char *filename;
for(;;) {
UWSGI_RELEASE_GIL;
sleep(up.auto_reload);
UWSGI_GET_GIL;
if (uwsgi.lazy || uwsgi.lazy_apps) {
// do not start monitoring til the first app is loaded (required for lazy mode)
if (uwsgi_apps_cnt == 0) continue;
}
#ifdef UWSGI_PYTHON_OLD
int pos = 0;
#else
Py_ssize_t pos = 0;
#endif
PyObject *mod_name, *mod;
while (PyDict_Next(modules, &pos, &mod_name, &mod)) {
if (mod == NULL) continue;
int found = 0;
struct uwsgi_string_list *usl = up.auto_reload_ignore;
while(usl) {
#ifdef PYTHREE
PyObject *zero = PyUnicode_AsUTF8String(mod_name);
char *str_mod_name = PyString_AsString(zero);
int ret_cmp = strcmp(usl->value, str_mod_name);
Py_DECREF(zero);
if (!ret_cmp) {
#else
if (!strcmp(usl->value, PyString_AsString(mod_name))) {
#endif
found = 1;
break;
}
usl = usl->next;
}
if (found) continue;
if (!PyObject_HasAttrString(mod, "__file__")) continue;
PyObject *mod_file = PyObject_GetAttrString(mod, "__file__");
if (!mod_file) continue;
if (mod_file == Py_None) continue;
#ifdef PYTHREE
PyObject *zero = PyUnicode_AsUTF8String(mod_file);
char *mod_filename = PyString_AsString(zero);
#else
char *mod_filename = PyString_AsString(mod_file);
#endif
if (!mod_filename) {
#ifdef PYTHREE
Py_DECREF(zero);
#endif
continue;
}
char *ext = strrchr(mod_filename, '.');
if (ext && (!strcmp(ext+1, "pyc") || !strcmp(ext+1, "pyd") || !strcmp(ext+1, "pyo"))) {
filename = uwsgi_concat2n(mod_filename, strlen(mod_filename)-1, "", 0);
}
else {
filename = uwsgi_concat2(mod_filename, "");
}
if (uwsgi_check_python_mtime(times_dict, filename)) {
UWSGI_RELEASE_GIL;
return NULL;
}
free(filename);
#ifdef PYTHREE
Py_DECREF(zero);
#endif
}
}
return NULL;
}
void uwsgi_python_suspend(struct wsgi_request *wsgi_req) {
PyGILState_STATE pgst = PyGILState_Ensure();
PyThreadState *tstate = PyThreadState_GET();
PyGILState_Release(pgst);
if (wsgi_req) {
#ifdef UWSGI_PY314
up.current_py_recursion_remaining[wsgi_req->async_id] = tstate->py_recursion_remaining;
up.current_frame[wsgi_req->async_id] = tstate->current_frame;
#elif defined UWSGI_PY313
up.current_c_recursion_remaining[wsgi_req->async_id] = tstate->c_recursion_remaining;
up.current_py_recursion_remaining[wsgi_req->async_id] = tstate->py_recursion_remaining;
up.current_frame[wsgi_req->async_id] = tstate->current_frame;
#elif defined UWSGI_PY312
up.current_c_recursion_remaining[wsgi_req->async_id] = tstate->c_recursion_remaining;
up.current_py_recursion_remaining[wsgi_req->async_id] = tstate->py_recursion_remaining;
up.current_frame[wsgi_req->async_id] = tstate->cframe;
#elif defined UWSGI_PY311
up.current_recursion_remaining[wsgi_req->async_id] = tstate->recursion_remaining;
up.current_frame[wsgi_req->async_id] = tstate->cframe;
#else
up.current_recursion_depth[wsgi_req->async_id] = tstate->recursion_depth;
up.current_frame[wsgi_req->async_id] = tstate->frame;
#endif
}
else {
#ifdef UWSGI_PY314
up.current_main_py_recursion_remaining = tstate->py_recursion_remaining;
up.current_main_frame = tstate->current_frame;
#elif defined UWSGI_PY313
up.current_main_c_recursion_remaining = tstate->c_recursion_remaining;
up.current_main_py_recursion_remaining = tstate->py_recursion_remaining;
up.current_main_frame = tstate->current_frame;
#elif defined UWSGI_PY312
up.current_main_c_recursion_remaining = tstate->c_recursion_remaining;
up.current_main_py_recursion_remaining = tstate->py_recursion_remaining;
up.current_main_frame = tstate->cframe;
#elif defined UWSGI_PY311
up.current_main_recursion_remaining = tstate->recursion_remaining;
up.current_main_frame = tstate->cframe;
#else
up.current_main_recursion_depth = tstate->recursion_depth;
up.current_main_frame = tstate->frame;
#endif
}
}
char *uwsgi_python_code_string(char *id, char *code, char *function, char *key, uint16_t keylen) {
PyObject *cs_module = NULL;
PyObject *cs_dict = NULL;
UWSGI_GET_GIL;
cs_module = PyImport_ImportModule(id);
if (!cs_module) {
PyErr_Clear();
cs_module = uwsgi_pyimport_by_filename(id, code);
}
if (!cs_module) {
UWSGI_RELEASE_GIL;
return NULL;
}
cs_dict = PyModule_GetDict(cs_module);
if (!cs_dict) {
PyErr_Print();
UWSGI_RELEASE_GIL;
return NULL;
}
PyObject *func = PyDict_GetItemString(cs_dict, function);
if (!func) {
uwsgi_log("function %s not available in %s\n", function, code);
PyErr_Print();
UWSGI_RELEASE_GIL;
return NULL;
}
PyObject *args = PyTuple_New(1);
PyTuple_SetItem(args, 0, PyString_FromStringAndSize(key, keylen));
PyObject *ret = python_call(func, args, 0, NULL);
Py_DECREF(args);
if (ret && PyString_Check(ret)) {
char *val = PyString_AsString(ret);
UWSGI_RELEASE_GIL;
return val;
}
UWSGI_RELEASE_GIL;
return NULL;
}
int uwsgi_python_signal_handler(uint8_t sig, void *handler) {
UWSGI_GET_GIL;
PyObject *args = PyTuple_New(1);
PyObject *ret;
if (!args)
goto clear;
if (!handler) goto clear;
PyTuple_SetItem(args, 0, PyInt_FromLong(sig));
ret = python_call(handler, args, 0, NULL);
Py_DECREF(args);
if (ret) {
Py_DECREF(ret);
UWSGI_RELEASE_GIL;
return 0;
}
clear:
UWSGI_RELEASE_GIL;
return -1;
}
uint64_t uwsgi_python_rpc(void *func, uint8_t argc, char **argv, uint16_t argvs[], char **buffer) {
UWSGI_GET_GIL;
uint8_t i;
char *rv;
size_t rl;
PyObject *pyargs = PyTuple_New(argc);
PyObject *ret;
if (!pyargs) {
UWSGI_RELEASE_GIL;
return 0;
}
for (i = 0; i < argc; i++) {
PyTuple_SetItem(pyargs, i, PyString_FromStringAndSize(argv[i], argvs[i]));
}
ret = python_call((PyObject *) func, pyargs, 0, NULL);
Py_DECREF(pyargs);
if (ret) {
if (PyString_Check(ret)) {
rv = PyString_AsString(ret);
rl = PyString_Size(ret);
if (rl > 0) {
*buffer = uwsgi_malloc(rl);
memcpy(*buffer, rv, rl);
Py_DECREF(ret);
UWSGI_RELEASE_GIL;
return rl;
}
}
Py_DECREF(ret);
}
if (PyErr_Occurred())
PyErr_Print();
UWSGI_RELEASE_GIL;
return 0;
}
void uwsgi_python_add_item(char *key, uint16_t keylen, char *val, uint16_t vallen, void *data) {
PyObject *pydict = (PyObject *) data;
PyObject *o_key = PyString_FromStringAndSize(key, keylen);
PyObject *zero = PyString_FromStringAndSize(val, vallen);
PyDict_SetItem(pydict, o_key, zero);
Py_DECREF(o_key);
Py_DECREF(zero);
}
PyObject *uwsgi_python_dict_from_spooler_content(char *filename, char *buf, uint16_t len, char *body, size_t body_len) {
PyObject *spool_dict = PyDict_New();
PyObject *value = PyString_FromString(filename);
PyDict_SetItemString(spool_dict, "spooler_task_name", value);
Py_DECREF(value);
if (uwsgi_hooked_parse(buf, len, uwsgi_python_add_item, spool_dict))
return NULL;
if (body && body_len > 0) {
PyObject *value = PyString_FromStringAndSize(body, body_len);
PyDict_SetItemString(spool_dict, "body", value);
Py_DECREF(value);
}
return spool_dict;
}
int uwsgi_python_spooler(char *filename, char *buf, uint16_t len, char *body, size_t body_len) {
static int random_seed_reset = 0;
UWSGI_GET_GIL;
if (!random_seed_reset) {
uwsgi_python_reset_random_seed();
random_seed_reset = 1;
}
if (!up.embedded_dict) {
// ignore
UWSGI_RELEASE_GIL;
return 0;
}
PyObject *spool_func = PyDict_GetItemString(up.embedded_dict, "spooler");
if (!spool_func) {
// ignore
UWSGI_RELEASE_GIL;
return 0;
}
int retval = -1;
PyObject *pyargs = PyTuple_New(1);
PyObject *ret = NULL;
PyObject *spool_dict = uwsgi_python_dict_from_spooler_content(filename, buf, len, body, body_len);
if (!spool_dict) {
retval = -2;
goto clear;
}
// PyTuple_SetItem steals a reference !!!
Py_INCREF(spool_dict);
PyTuple_SetItem(pyargs, 0, spool_dict);
ret = python_call(spool_func, pyargs, 0, NULL);
if (ret) {
if (!PyInt_Check(ret)) {
retval = -1; // error, retry
} else {
retval = (int) PyInt_AsLong(ret);
}
goto clear;
}
if (PyErr_Occurred())
PyErr_Print();
// error, retry
retval = -1;
clear:
Py_XDECREF(ret);
Py_XDECREF(pyargs);
Py_XDECREF(spool_dict);
UWSGI_RELEASE_GIL;
return retval;
}
void uwsgi_python_resume(struct wsgi_request *wsgi_req) {
PyGILState_STATE pgst = PyGILState_Ensure();
PyThreadState *tstate = PyThreadState_GET();
PyGILState_Release(pgst);
if (wsgi_req) {
#ifdef UWSGI_PY314
tstate->py_recursion_remaining = up.current_py_recursion_remaining[wsgi_req->async_id];
tstate->current_frame = up.current_frame[wsgi_req->async_id];
#elif defined UWSGI_PY313
tstate->c_recursion_remaining = up.current_c_recursion_remaining[wsgi_req->async_id];
tstate->py_recursion_remaining = up.current_py_recursion_remaining[wsgi_req->async_id];
tstate->current_frame = up.current_frame[wsgi_req->async_id];
#elif defined UWSGI_PY312
tstate->c_recursion_remaining = up.current_c_recursion_remaining[wsgi_req->async_id];
tstate->py_recursion_remaining = up.current_py_recursion_remaining[wsgi_req->async_id];
tstate->cframe = up.current_frame[wsgi_req->async_id];
#elif defined UWSGI_PY311
tstate->recursion_remaining = up.current_recursion_remaining[wsgi_req->async_id];
tstate->cframe = up.current_frame[wsgi_req->async_id];
#else
tstate->recursion_depth = up.current_recursion_depth[wsgi_req->async_id];
tstate->frame = up.current_frame[wsgi_req->async_id];
#endif
}
else {
#ifdef UWSGI_PY314
tstate->py_recursion_remaining = up.current_main_py_recursion_remaining;
tstate->current_frame = up.current_main_frame;
#elif defined UWSGI_PY313
tstate->c_recursion_remaining = up.current_main_c_recursion_remaining;
tstate->py_recursion_remaining = up.current_main_py_recursion_remaining;
tstate->current_frame = up.current_main_frame;
#elif defined UWSGI_PY312
tstate->c_recursion_remaining = up.current_main_c_recursion_remaining;
tstate->py_recursion_remaining = up.current_main_py_recursion_remaining;
tstate->cframe = up.current_main_frame;
#elif defined UWSGI_PY311
tstate->recursion_remaining = up.current_main_recursion_remaining;
tstate->cframe = up.current_main_frame;
#else
tstate->recursion_depth = up.current_main_recursion_depth;
tstate->frame = up.current_main_frame;
#endif
}
}
void uwsgi_python_fixup() {
// set hacky modifier 30
uwsgi.p[30] = uwsgi_malloc( sizeof(struct uwsgi_plugin) );
memcpy(uwsgi.p[30], uwsgi.p[0], sizeof(struct uwsgi_plugin) );
uwsgi.p[30]->init_thread = NULL;
uwsgi.p[30]->atexit = NULL;
}
void uwsgi_python_hijack(void) {
// the pyshell will be execute only in the first worker
FILE *pyfile;
if (up.pyrun) {
uwsgi.workers[uwsgi.mywid].hijacked = 1;
UWSGI_GET_GIL;
pyfile = fopen(up.pyrun, "r");
if (!pyfile) {
uwsgi_error_open(up.pyrun);
exit(1);
}
PyRun_SimpleFile(pyfile, up.pyrun);
// could be never executed
exit(0);
}
if (up.pyshell_oneshot && uwsgi.workers[uwsgi.mywid].hijacked_count > 0) {
uwsgi.workers[uwsgi.mywid].hijacked = 0;
return;
}
if (up.pyshell && uwsgi.mywid == 1) {
uwsgi.workers[uwsgi.mywid].hijacked = 1;
uwsgi.workers[uwsgi.mywid].hijacked_count++;
// re-map stdin to stdout and stderr if we are logging to a file
if (uwsgi.logfile) {
if (dup2(0, 1) < 0) {
uwsgi_error("dup2()");
}
if (dup2(0, 2) < 0) {
uwsgi_error("dup2()");
}
}
UWSGI_GET_GIL;
int ret = -1;
if (up.pyshell[0] != 0) {
ret = PyRun_SimpleString(up.pyshell);
}
else {
PyImport_ImportModule("readline");
ret = PyRun_InteractiveLoop(stdin, "uwsgi");
}
if (up.pyshell_oneshot) {
exit(UWSGI_DE_HIJACKED_CODE);
}
if (ret == 0) {
exit(UWSGI_QUIET_CODE);
}
exit(0);
}
}
int uwsgi_python_mule(char *opt) {
if (uwsgi_endswith(opt, ".py")) {
UWSGI_GET_GIL;
uwsgi_pyimport_by_filename("__main__", opt);
UWSGI_RELEASE_GIL;
return 1;
}
else if (strchr(opt, ':')) {
UWSGI_GET_GIL;
PyObject *result = NULL;
PyObject *arglist = Py_BuildValue("()");
PyObject *callable = up.loaders[LOADER_MOUNT](opt);
if (callable) {
result = PyObject_CallObject(callable, arglist);
}
Py_XDECREF(result);
Py_XDECREF(arglist);
Py_XDECREF(callable);
UWSGI_RELEASE_GIL;
return 1;
}
return 0;
}
int uwsgi_python_mule_msg(char *message, size_t len) {
UWSGI_GET_GIL;
PyObject *mule_msg_hook = PyDict_GetItemString(up.embedded_dict, "mule_msg_hook");
if (!mule_msg_hook) {
// ignore
UWSGI_RELEASE_GIL;
return 0;
}
PyObject *pyargs = PyTuple_New(1);
PyTuple_SetItem(pyargs, 0, PyString_FromStringAndSize(message, len));
PyObject *ret = python_call(mule_msg_hook, pyargs, 0, NULL);
Py_DECREF(pyargs);
if (ret) {
Py_DECREF(ret);
}
if (PyErr_Occurred())
PyErr_Print();
UWSGI_RELEASE_GIL;
return 1;
}
static void uwsgi_python_harakiri(int wid) {
if (up.tracebacker) {
char buf[8192];
char *wid_str = uwsgi_num2str(wid);
char *address = uwsgi_concat2(up.tracebacker, wid_str);
int fd = uwsgi_connect(address, -1, 0);
if (fd < 1)
goto exit;
for(;;) {
int ret = uwsgi_waitfd(fd, uwsgi.socket_timeout);
if (ret <= 0) goto cleanup;
ssize_t len = read(fd, buf, 8192);
if (len <= 0) goto cleanup;
uwsgi_log("%.*s", (int) len, buf);
}
cleanup:
close(fd);
exit:
free(wid_str);
free(address);
}
}
/*
# you can use this logger to offload logging to python
# be sure to configure it to not log to stderr otherwise you will generate a loop
import logging
logging.basicConfig(filename='/tmp/pippo.log')
*/
static ssize_t uwsgi_python_logger(struct uwsgi_logger *ul, char *message, size_t len) {
if (!Py_IsInitialized()) return -1;
UWSGI_GET_GIL
if (!ul->configured) {
PyObject *py_logging = PyImport_ImportModule("logging");
if (!py_logging) goto clear;
PyObject *py_logging_dict = PyModule_GetDict(py_logging);
if (!py_logging_dict) goto clear;
PyObject *py_getLogger = PyDict_GetItemString(py_logging_dict, "getLogger");
if (!py_getLogger) goto clear;
PyObject *py_getLogger_args = NULL;
if (ul->arg) {
py_getLogger_args = PyTuple_New(1);
PyTuple_SetItem(py_getLogger_args, 0, UWSGI_PYFROMSTRING(ul->arg));
}
ul->data = (void *) PyObject_CallObject(py_getLogger, py_getLogger_args);
if (PyErr_Occurred()) {
PyErr_Clear();
}
Py_XDECREF(py_getLogger_args);
if (!ul->data) goto clear;
ul->configured = 1;
}
PyObject_CallMethod((PyObject *) ul->data, "error", "(s#)", message, len);
if (PyErr_Occurred()) {
PyErr_Clear();
}
UWSGI_RELEASE_GIL
return len;
clear:
UWSGI_RELEASE_GIL
return -1;
}
static void uwsgi_python_on_load() {
uwsgi_register_logger("python", uwsgi_python_logger);
}
static int uwsgi_python_worker() {
if (!up.worker_override)
return 0;
UWSGI_GET_GIL;
// ensure signals can be used again from python
// Necessary if fork hooks have been not used to update interpreter state
if (!up.call_osafterfork && !up.call_uwsgi_fork_hooks)
#ifdef HAS_NOT_PYOS_FORK_STABLE_API
PyOS_AfterFork();
#else
PyOS_AfterFork_Child();
#endif
FILE *pyfile = fopen(up.worker_override, "r");
if (!pyfile) {
uwsgi_error_open(up.worker_override);
exit(1);
}
PyRun_SimpleFile(pyfile, up.worker_override);
return 1;
}
struct uwsgi_plugin python_plugin = {
.name = "python",
.alias = "python",
.modifier1 = 0,
.init = uwsgi_python_init,
.post_fork = uwsgi_python_post_fork,
.options = uwsgi_python_options,
.request = uwsgi_request_wsgi,
.after_request = uwsgi_after_request_wsgi,
.preinit_apps = uwsgi_python_preinit_apps,
.init_apps = uwsgi_python_init_apps,
.fixup = uwsgi_python_fixup,
.master_fixup = uwsgi_python_master_fixup,
.mount_app = uwsgi_python_mount_app,
.enable_threads = uwsgi_python_enable_threads,
.init_thread = uwsgi_python_init_thread,
.magic = uwsgi_python_magic,
.suspend = uwsgi_python_suspend,
.resume = uwsgi_python_resume,
.harakiri = uwsgi_python_harakiri,
.hijack_worker = uwsgi_python_hijack,
.spooler_init = uwsgi_python_spooler_init,
.signal_handler = uwsgi_python_signal_handler,
.rpc = uwsgi_python_rpc,
.mule = uwsgi_python_mule,
.mule_msg = uwsgi_python_mule_msg,
.on_load = uwsgi_python_on_load,
.spooler = uwsgi_python_spooler,
.atexit = uwsgi_python_atexit,
.code_string = uwsgi_python_code_string,
.exception_class = uwsgi_python_exception_class,
.exception_msg = uwsgi_python_exception_msg,
.exception_repr = uwsgi_python_exception_repr,
.exception_log = uwsgi_python_exception_log,
.backtrace = uwsgi_python_backtrace,
.worker = uwsgi_python_worker,
.pre_uwsgi_fork = uwsgi_python_pre_uwsgi_fork,
.post_uwsgi_fork = uwsgi_python_post_uwsgi_fork,
};
|