1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988
|
// Copyright 2013-2025 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"bytes"
"cmp"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"encoding/json"
"expvar"
"fmt"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"slices"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/nats-io/jwt/v2"
"github.com/nats-io/nats-server/v2/server/pse"
)
// Connz represents detailed information on current client connections.
type Connz struct {
ID string `json:"server_id"`
Now time.Time `json:"now"`
NumConns int `json:"num_connections"`
Total int `json:"total"`
Offset int `json:"offset"`
Limit int `json:"limit"`
Conns []*ConnInfo `json:"connections"`
}
// ConnzOptions are the options passed to Connz()
type ConnzOptions struct {
// Sort indicates how the results will be sorted. Check SortOpt for possible values.
// Only the sort by connection ID (ByCid) is ascending, all others are descending.
Sort SortOpt `json:"sort"`
// Username indicates if user names should be included in the results.
Username bool `json:"auth"`
// Subscriptions indicates if subscriptions should be included in the results.
Subscriptions bool `json:"subscriptions"`
// SubscriptionsDetail indicates if subscription details should be included in the results
SubscriptionsDetail bool `json:"subscriptions_detail"`
// Offset is used for pagination. Connz() only returns connections starting at this
// offset from the global results.
Offset int `json:"offset"`
// Limit is the maximum number of connections that should be returned by Connz().
Limit int `json:"limit"`
// Filter for this explicit client connection.
CID uint64 `json:"cid"`
// Filter for this explicit client connection based on the MQTT client ID
MQTTClient string `json:"mqtt_client"`
// Filter by connection state.
State ConnState `json:"state"`
// The below options only apply if auth is true.
// Filter by username.
User string `json:"user"`
// Filter by account.
Account string `json:"acc"`
// Filter by subject interest
FilterSubject string `json:"filter_subject"`
}
// ConnState is for filtering states of connections. We will only have two, open and closed.
type ConnState int
const (
// ConnOpen filters on open clients.
ConnOpen = ConnState(iota)
// ConnClosed filters on closed clients.
ConnClosed
// ConnAll returns all clients.
ConnAll
)
// ConnInfo has detailed information on a per connection basis.
type ConnInfo struct {
Cid uint64 `json:"cid"`
Kind string `json:"kind,omitempty"`
Type string `json:"type,omitempty"`
IP string `json:"ip"`
Port int `json:"port"`
Start time.Time `json:"start"`
LastActivity time.Time `json:"last_activity"`
Stop *time.Time `json:"stop,omitempty"`
Reason string `json:"reason,omitempty"`
RTT string `json:"rtt,omitempty"`
Uptime string `json:"uptime"`
Idle string `json:"idle"`
Pending int `json:"pending_bytes"`
InMsgs int64 `json:"in_msgs"`
OutMsgs int64 `json:"out_msgs"`
InBytes int64 `json:"in_bytes"`
OutBytes int64 `json:"out_bytes"`
NumSubs uint32 `json:"subscriptions"`
Name string `json:"name,omitempty"`
Lang string `json:"lang,omitempty"`
Version string `json:"version,omitempty"`
TLSVersion string `json:"tls_version,omitempty"`
TLSCipher string `json:"tls_cipher_suite,omitempty"`
TLSPeerCerts []*TLSPeerCert `json:"tls_peer_certs,omitempty"`
TLSFirst bool `json:"tls_first,omitempty"`
AuthorizedUser string `json:"authorized_user,omitempty"`
Account string `json:"account,omitempty"`
Subs []string `json:"subscriptions_list,omitempty"`
SubsDetail []SubDetail `json:"subscriptions_list_detail,omitempty"`
JWT string `json:"jwt,omitempty"`
IssuerKey string `json:"issuer_key,omitempty"`
NameTag string `json:"name_tag,omitempty"`
Tags jwt.TagList `json:"tags,omitempty"`
MQTTClient string `json:"mqtt_client,omitempty"` // This is the MQTT client id
// Internal
rtt int64 // For fast sorting
}
// TLSPeerCert contains basic information about a TLS peer certificate
type TLSPeerCert struct {
Subject string `json:"subject,omitempty"`
SubjectPKISha256 string `json:"spki_sha256,omitempty"`
CertSha256 string `json:"cert_sha256,omitempty"`
}
// DefaultConnListSize is the default size of the connection list.
const DefaultConnListSize = 1024
// DefaultSubListSize is the default size of the subscriptions list.
const DefaultSubListSize = 1024
const defaultStackBufSize = 10000
func newSubsDetailList(client *client) []SubDetail {
subsDetail := make([]SubDetail, 0, len(client.subs))
for _, sub := range client.subs {
subsDetail = append(subsDetail, newClientSubDetail(sub))
}
return subsDetail
}
func newSubsList(client *client) []string {
subs := make([]string, 0, len(client.subs))
for _, sub := range client.subs {
subs = append(subs, string(sub.subject))
}
return subs
}
// Connz returns a Connz struct containing information about connections.
func (s *Server) Connz(opts *ConnzOptions) (*Connz, error) {
var (
sortOpt = ByCid
auth bool
subs bool
subsDet bool
offset int
limit = DefaultConnListSize
cid = uint64(0)
state = ConnOpen
user string
acc string
a *Account
filter string
mqttCID string
)
if opts != nil {
// If no sort option given or sort is by uptime, then sort by cid
if opts.Sort != _EMPTY_ {
sortOpt = opts.Sort
if !sortOpt.IsValid() {
return nil, fmt.Errorf("invalid sorting option: %s", sortOpt)
}
}
// Auth specifics.
auth = opts.Username
user = opts.User
acc = opts.Account
mqttCID = opts.MQTTClient
subs = opts.Subscriptions
subsDet = opts.SubscriptionsDetail
offset = opts.Offset
if offset < 0 {
offset = 0
}
limit = opts.Limit
if limit <= 0 {
limit = DefaultConnListSize
}
// state
state = opts.State
// ByStop only makes sense on closed connections
if sortOpt == ByStop && state != ConnClosed {
return nil, fmt.Errorf("sort by stop only valid on closed connections")
}
// ByReason is the same.
if sortOpt == ByReason && state != ConnClosed {
return nil, fmt.Errorf("sort by reason only valid on closed connections")
}
// If searching by CID
if opts.CID > 0 {
cid = opts.CID
limit = 1
}
// If filtering by subject.
if opts.FilterSubject != _EMPTY_ && opts.FilterSubject != fwcs {
if acc == _EMPTY_ {
return nil, fmt.Errorf("filter by subject only valid with account filtering")
}
filter = opts.FilterSubject
}
}
c := &Connz{
Offset: offset,
Limit: limit,
Now: time.Now().UTC(),
}
// Open clients
var openClients []*client
// Hold for closed clients if requested.
var closedClients []*closedClient
var clist map[uint64]*client
if acc != _EMPTY_ {
var err error
a, err = s.lookupAccount(acc)
if err != nil {
return c, nil
}
a.mu.RLock()
clist = make(map[uint64]*client, a.numLocalConnections())
for c := range a.clients {
if c.kind == CLIENT || c.kind == LEAF {
clist[c.cid] = c
}
}
a.mu.RUnlock()
}
// Walk the open client list with server lock held.
s.mu.RLock()
// Default to all client unless filled in above.
if clist == nil {
clist = s.clients
}
// copy the server id for monitoring
c.ID = s.info.ID
// Number of total clients. The resulting ConnInfo array
// may be smaller if pagination is used.
switch state {
case ConnOpen:
c.Total = len(clist)
case ConnClosed:
closedClients = s.closed.closedClients()
c.Total = len(closedClients)
case ConnAll:
c.Total = len(clist)
closedClients = s.closed.closedClients()
c.Total += len(closedClients)
}
// We may need to filter these connections.
if acc != _EMPTY_ && len(closedClients) > 0 {
var ccc []*closedClient
for _, cc := range closedClients {
if cc.acc != acc {
continue
}
ccc = append(ccc, cc)
}
c.Total -= (len(closedClients) - len(ccc))
closedClients = ccc
}
totalClients := c.Total
if cid > 0 { // Meaning we only want 1.
totalClients = 1
}
if state == ConnOpen || state == ConnAll {
openClients = make([]*client, 0, totalClients)
}
// Data structures for results.
var conns []ConnInfo // Limits allocs for actual ConnInfos.
var pconns ConnInfos
switch state {
case ConnOpen:
conns = make([]ConnInfo, totalClients)
pconns = make(ConnInfos, totalClients)
case ConnClosed:
pconns = make(ConnInfos, totalClients)
case ConnAll:
conns = make([]ConnInfo, cap(openClients))
pconns = make(ConnInfos, totalClients)
}
// Search by individual CID.
if cid > 0 {
if state == ConnClosed || state == ConnAll {
copyClosed := closedClients
closedClients = nil
for _, cc := range copyClosed {
if cc.Cid == cid {
closedClients = []*closedClient{cc}
break
}
}
} else if state == ConnOpen || state == ConnAll {
client := s.clients[cid]
if client != nil {
openClients = append(openClients, client)
}
}
} else {
// Gather all open clients.
if state == ConnOpen || state == ConnAll {
for _, client := range clist {
// If we have an account specified we need to filter.
if acc != _EMPTY_ && (client.acc == nil || client.acc.Name != acc) {
continue
}
// Do user filtering second
if user != _EMPTY_ && client.getRawAuthUserLock() != user {
continue
}
// Do mqtt client ID filtering next
if mqttCID != _EMPTY_ && client.getMQTTClientID() != mqttCID {
continue
}
openClients = append(openClients, client)
}
}
}
s.mu.RUnlock()
// Filter by subject now if needed. We do this outside of server lock.
if filter != _EMPTY_ {
var oc []*client
for _, c := range openClients {
c.mu.Lock()
for _, sub := range c.subs {
if SubjectsCollide(filter, string(sub.subject)) {
oc = append(oc, c)
break
}
}
c.mu.Unlock()
openClients = oc
}
}
// Just return with empty array if nothing here.
if len(openClients) == 0 && len(closedClients) == 0 {
c.Conns = ConnInfos{}
return c, nil
}
// Now whip through and generate ConnInfo entries
// Open Clients
i := 0
for _, client := range openClients {
client.mu.Lock()
ci := &conns[i]
ci.fill(client, client.nc, c.Now, auth)
// Fill in subscription data if requested.
if len(client.subs) > 0 {
if subsDet {
ci.SubsDetail = newSubsDetailList(client)
} else if subs {
ci.Subs = newSubsList(client)
}
}
// Fill in user if auth requested.
if auth {
ci.AuthorizedUser = client.getRawAuthUser()
// Add in account iff not the global account.
if client.acc != nil && (client.acc.Name != globalAccountName) {
ci.Account = client.acc.Name
}
ci.JWT = client.opts.JWT
ci.IssuerKey = issuerForClient(client)
ci.Tags = client.tags
ci.NameTag = client.nameTag
}
client.mu.Unlock()
pconns[i] = ci
i++
}
// Closed Clients
var needCopy bool
if subs || auth {
needCopy = true
}
for _, cc := range closedClients {
// If we have an account specified we need to filter.
if acc != _EMPTY_ && cc.acc != acc {
continue
}
// Do user filtering second
if user != _EMPTY_ && cc.user != user {
continue
}
// Do mqtt client ID filtering next
if mqttCID != _EMPTY_ && cc.MQTTClient != mqttCID {
continue
}
// Copy if needed for any changes to the ConnInfo
if needCopy {
cx := *cc
cc = &cx
}
// Fill in subscription data if requested.
if len(cc.subs) > 0 {
if subsDet {
cc.SubsDetail = cc.subs
} else if subs {
cc.Subs = make([]string, 0, len(cc.subs))
for _, sub := range cc.subs {
cc.Subs = append(cc.Subs, sub.Subject)
}
}
}
// Fill in user if auth requested.
if auth {
cc.AuthorizedUser = cc.user
// Add in account iff not the global account.
if cc.acc != _EMPTY_ && (cc.acc != globalAccountName) {
cc.Account = cc.acc
}
}
pconns[i] = &cc.ConnInfo
i++
}
// This will trip if we have filtered out client connections.
if len(pconns) != i {
pconns = pconns[:i]
totalClients = i
}
switch sortOpt {
case ByCid, ByStart:
sort.Sort(byCid{pconns})
case BySubs:
sort.Sort(sort.Reverse(bySubs{pconns}))
case ByPending:
sort.Sort(sort.Reverse(byPending{pconns}))
case ByOutMsgs:
sort.Sort(sort.Reverse(byOutMsgs{pconns}))
case ByInMsgs:
sort.Sort(sort.Reverse(byInMsgs{pconns}))
case ByOutBytes:
sort.Sort(sort.Reverse(byOutBytes{pconns}))
case ByInBytes:
sort.Sort(sort.Reverse(byInBytes{pconns}))
case ByLast:
sort.Sort(sort.Reverse(byLast{pconns}))
case ByIdle:
sort.Sort(sort.Reverse(byIdle{pconns, c.Now}))
case ByUptime:
sort.Sort(byUptime{pconns, time.Now()})
case ByStop:
sort.Sort(sort.Reverse(byStop{pconns}))
case ByReason:
sort.Sort(byReason{pconns})
case ByRTT:
sort.Sort(sort.Reverse(byRTT{pconns}))
}
minoff := c.Offset
maxoff := c.Offset + c.Limit
maxIndex := totalClients
// Make sure these are sane.
if minoff > maxIndex {
minoff = maxIndex
}
if maxoff > maxIndex {
maxoff = maxIndex
}
// Now pare down to the requested size.
// TODO(dlc) - for very large number of connections we
// could save the whole list in a hash, send hash on first
// request and allow users to use has for subsequent pages.
// Low TTL, say < 1sec.
c.Conns = pconns[minoff:maxoff]
c.NumConns = len(c.Conns)
return c, nil
}
// Fills in the ConnInfo from the client.
// client should be locked.
func (ci *ConnInfo) fill(client *client, nc net.Conn, now time.Time, auth bool) {
// For fast sort if required.
rtt := client.getRTT()
ci.rtt = int64(rtt)
ci.Cid = client.cid
ci.MQTTClient = client.getMQTTClientID()
ci.Kind = client.kindString()
ci.Type = client.clientTypeString()
ci.Start = client.start
ci.LastActivity = client.last
ci.Uptime = myUptime(now.Sub(client.start))
ci.Idle = myUptime(now.Sub(client.last))
ci.RTT = rtt.String()
ci.OutMsgs = client.outMsgs
ci.OutBytes = client.outBytes
ci.NumSubs = uint32(len(client.subs))
ci.Pending = int(client.out.pb)
ci.Name = client.opts.Name
ci.Lang = client.opts.Lang
ci.Version = client.opts.Version
// inMsgs and inBytes are updated outside of the client's lock, so
// we need to use atomic here.
ci.InMsgs = atomic.LoadInt64(&client.inMsgs)
ci.InBytes = atomic.LoadInt64(&client.inBytes)
// If the connection is gone, too bad, we won't set TLSVersion and TLSCipher.
// Exclude clients that are still doing handshake so we don't block in
// ConnectionState().
if client.flags.isSet(handshakeComplete) && nc != nil {
if conn, ok := nc.(*tls.Conn); ok {
cs := conn.ConnectionState()
ci.TLSVersion = tlsVersion(cs.Version)
ci.TLSCipher = tlsCipher(cs.CipherSuite)
if auth && len(cs.PeerCertificates) > 0 {
ci.TLSPeerCerts = makePeerCerts(cs.PeerCertificates)
}
ci.TLSFirst = client.flags.isSet(didTLSFirst)
}
}
if client.port != 0 {
ci.Port = int(client.port)
ci.IP = client.host
}
}
func makePeerCerts(pc []*x509.Certificate) []*TLSPeerCert {
res := make([]*TLSPeerCert, len(pc))
for i, c := range pc {
tmp := sha256.Sum256(c.RawSubjectPublicKeyInfo)
ssha := hex.EncodeToString(tmp[:])
tmp = sha256.Sum256(c.Raw)
csha := hex.EncodeToString(tmp[:])
res[i] = &TLSPeerCert{Subject: c.Subject.String(), SubjectPKISha256: ssha, CertSha256: csha}
}
return res
}
// Assume lock is held
func (c *client) getRTT() time.Duration {
if c.rtt == 0 {
// If a real client, go ahead and send ping now to get a value
// for RTT. For tests and telnet, or if client is closing, etc skip.
if c.opts.Lang != _EMPTY_ {
c.sendRTTPingLocked()
}
return 0
}
var rtt time.Duration
if c.rtt > time.Microsecond && c.rtt < time.Millisecond {
rtt = c.rtt.Truncate(time.Microsecond)
} else {
rtt = c.rtt.Truncate(time.Nanosecond)
}
return rtt
}
func decodeBool(w http.ResponseWriter, r *http.Request, param string) (bool, error) {
str := r.URL.Query().Get(param)
if str == _EMPTY_ {
return false, nil
}
val, err := strconv.ParseBool(str)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(fmt.Sprintf("Error decoding boolean for '%s': %v", param, err)))
return false, err
}
return val, nil
}
func decodeUint64(w http.ResponseWriter, r *http.Request, param string) (uint64, error) {
str := r.URL.Query().Get(param)
if str == _EMPTY_ {
return 0, nil
}
val, err := strconv.ParseUint(str, 10, 64)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(fmt.Sprintf("Error decoding uint64 for '%s': %v", param, err)))
return 0, err
}
return val, nil
}
func decodeInt(w http.ResponseWriter, r *http.Request, param string) (int, error) {
str := r.URL.Query().Get(param)
if str == _EMPTY_ {
return 0, nil
}
val, err := strconv.Atoi(str)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(fmt.Sprintf("Error decoding int for '%s': %v", param, err)))
return 0, err
}
return val, nil
}
func decodeState(w http.ResponseWriter, r *http.Request) (ConnState, error) {
str := r.URL.Query().Get("state")
if str == _EMPTY_ {
return ConnOpen, nil
}
switch strings.ToLower(str) {
case "open":
return ConnOpen, nil
case "closed":
return ConnClosed, nil
case "any", "all":
return ConnAll, nil
}
// We do not understand intended state here.
w.WriteHeader(http.StatusBadRequest)
err := fmt.Errorf("Error decoding state for %s", str)
w.Write([]byte(err.Error()))
return 0, err
}
func decodeSubs(w http.ResponseWriter, r *http.Request) (subs bool, subsDet bool, err error) {
subsDet = strings.ToLower(r.URL.Query().Get("subs")) == "detail"
if !subsDet {
subs, err = decodeBool(w, r, "subs")
}
return
}
// HandleConnz process HTTP requests for connection information.
func (s *Server) HandleConnz(w http.ResponseWriter, r *http.Request) {
sortOpt := SortOpt(r.URL.Query().Get("sort"))
auth, err := decodeBool(w, r, "auth")
if err != nil {
return
}
subs, subsDet, err := decodeSubs(w, r)
if err != nil {
return
}
offset, err := decodeInt(w, r, "offset")
if err != nil {
return
}
limit, err := decodeInt(w, r, "limit")
if err != nil {
return
}
cid, err := decodeUint64(w, r, "cid")
if err != nil {
return
}
state, err := decodeState(w, r)
if err != nil {
return
}
user := r.URL.Query().Get("user")
acc := r.URL.Query().Get("acc")
mqttCID := r.URL.Query().Get("mqtt_client")
connzOpts := &ConnzOptions{
Sort: sortOpt,
Username: auth,
Subscriptions: subs,
SubscriptionsDetail: subsDet,
Offset: offset,
Limit: limit,
CID: cid,
MQTTClient: mqttCID,
State: state,
User: user,
Account: acc,
}
s.mu.Lock()
s.httpReqStats[ConnzPath]++
s.mu.Unlock()
c, err := s.Connz(connzOpts)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
b, err := json.MarshalIndent(c, "", " ")
if err != nil {
s.Errorf("Error marshaling response to /connz request: %v", err)
}
// Handle response
ResponseHandler(w, r, b)
}
// Routez represents detailed information on current client connections.
type Routez struct {
ID string `json:"server_id"`
Name string `json:"server_name"`
Now time.Time `json:"now"`
Import *SubjectPermission `json:"import,omitempty"`
Export *SubjectPermission `json:"export,omitempty"`
NumRoutes int `json:"num_routes"`
Routes []*RouteInfo `json:"routes"`
}
// RoutezOptions are options passed to Routez
type RoutezOptions struct {
// Subscriptions indicates that Routez will return a route's subscriptions
Subscriptions bool `json:"subscriptions"`
// SubscriptionsDetail indicates if subscription details should be included in the results
SubscriptionsDetail bool `json:"subscriptions_detail"`
}
// RouteInfo has detailed information on a per connection basis.
type RouteInfo struct {
Rid uint64 `json:"rid"`
RemoteID string `json:"remote_id"`
RemoteName string `json:"remote_name"`
DidSolicit bool `json:"did_solicit"`
IsConfigured bool `json:"is_configured"`
IP string `json:"ip"`
Port int `json:"port"`
Start time.Time `json:"start"`
LastActivity time.Time `json:"last_activity"`
RTT string `json:"rtt,omitempty"`
Uptime string `json:"uptime"`
Idle string `json:"idle"`
Import *SubjectPermission `json:"import,omitempty"`
Export *SubjectPermission `json:"export,omitempty"`
Pending int `json:"pending_size"`
InMsgs int64 `json:"in_msgs"`
OutMsgs int64 `json:"out_msgs"`
InBytes int64 `json:"in_bytes"`
OutBytes int64 `json:"out_bytes"`
NumSubs uint32 `json:"subscriptions"`
Subs []string `json:"subscriptions_list,omitempty"`
SubsDetail []SubDetail `json:"subscriptions_list_detail,omitempty"`
Account string `json:"account,omitempty"`
Compression string `json:"compression,omitempty"`
}
// Routez returns a Routez struct containing information about routes.
func (s *Server) Routez(routezOpts *RoutezOptions) (*Routez, error) {
rs := &Routez{Routes: []*RouteInfo{}}
rs.Now = time.Now().UTC()
if routezOpts == nil {
routezOpts = &RoutezOptions{}
}
s.mu.Lock()
rs.NumRoutes = s.numRoutes()
// copy the server id for monitoring
rs.ID = s.info.ID
// Check for defined permissions for all connected routes.
if perms := s.getOpts().Cluster.Permissions; perms != nil {
rs.Import = perms.Import
rs.Export = perms.Export
}
rs.Name = s.getOpts().ServerName
addRoute := func(r *client) {
r.mu.Lock()
ri := &RouteInfo{
Rid: r.cid,
RemoteID: r.route.remoteID,
RemoteName: r.route.remoteName,
DidSolicit: r.route.didSolicit,
IsConfigured: r.route.routeType == Explicit,
InMsgs: atomic.LoadInt64(&r.inMsgs),
OutMsgs: r.outMsgs,
InBytes: atomic.LoadInt64(&r.inBytes),
OutBytes: r.outBytes,
NumSubs: uint32(len(r.subs)),
Import: r.opts.Import,
Pending: int(r.out.pb),
Export: r.opts.Export,
RTT: r.getRTT().String(),
Start: r.start,
LastActivity: r.last,
Uptime: myUptime(rs.Now.Sub(r.start)),
Idle: myUptime(rs.Now.Sub(r.last)),
Account: string(r.route.accName),
Compression: r.route.compression,
}
if len(r.subs) > 0 {
if routezOpts.SubscriptionsDetail {
ri.SubsDetail = newSubsDetailList(r)
} else if routezOpts.Subscriptions {
ri.Subs = newSubsList(r)
}
}
switch conn := r.nc.(type) {
case *net.TCPConn, *tls.Conn:
addr := conn.RemoteAddr().(*net.TCPAddr)
ri.Port = addr.Port
ri.IP = addr.IP.String()
}
r.mu.Unlock()
rs.Routes = append(rs.Routes, ri)
}
// Walk the list
s.forEachRoute(func(r *client) {
addRoute(r)
})
s.mu.Unlock()
return rs, nil
}
// HandleRoutez process HTTP requests for route information.
func (s *Server) HandleRoutez(w http.ResponseWriter, r *http.Request) {
subs, subsDetail, err := decodeSubs(w, r)
if err != nil {
return
}
opts := RoutezOptions{Subscriptions: subs, SubscriptionsDetail: subsDetail}
s.mu.Lock()
s.httpReqStats[RoutezPath]++
s.mu.Unlock()
// As of now, no error is ever returned.
rs, _ := s.Routez(&opts)
b, err := json.MarshalIndent(rs, "", " ")
if err != nil {
s.Errorf("Error marshaling response to /routez request: %v", err)
}
// Handle response
ResponseHandler(w, r, b)
}
// Subsz represents detail information on current connections.
type Subsz struct {
ID string `json:"server_id"`
Now time.Time `json:"now"`
*SublistStats
Total int `json:"total"`
Offset int `json:"offset"`
Limit int `json:"limit"`
Subs []SubDetail `json:"subscriptions_list,omitempty"`
}
// SubszOptions are the options passed to Subsz.
// As of now, there are no options defined.
type SubszOptions struct {
// Offset is used for pagination. Subsz() only returns connections starting at this
// offset from the global results.
Offset int `json:"offset"`
// Limit is the maximum number of subscriptions that should be returned by Subsz().
Limit int `json:"limit"`
// Subscriptions indicates if subscription details should be included in the results.
Subscriptions bool `json:"subscriptions"`
// Filter based on this account name.
Account string `json:"account,omitempty"`
// Test the list against this subject. Needs to be literal since it signifies a publish subject.
// We will only return subscriptions that would match if a message was sent to this subject.
Test string `json:"test,omitempty"`
}
// SubDetail is for verbose information for subscriptions.
type SubDetail struct {
Account string `json:"account,omitempty"`
Subject string `json:"subject"`
Queue string `json:"qgroup,omitempty"`
Sid string `json:"sid"`
Msgs int64 `json:"msgs"`
Max int64 `json:"max,omitempty"`
Cid uint64 `json:"cid"`
}
// Subscription client should be locked and guaranteed to be present.
func newSubDetail(sub *subscription) SubDetail {
sd := newClientSubDetail(sub)
if sub.client.acc != nil {
sd.Account = sub.client.acc.Name
}
return sd
}
// For subs details under clients.
func newClientSubDetail(sub *subscription) SubDetail {
return SubDetail{
Subject: string(sub.subject),
Queue: string(sub.queue),
Sid: string(sub.sid),
Msgs: sub.nm,
Max: sub.max,
Cid: sub.client.cid,
}
}
// Subsz returns a Subsz struct containing subjects statistics
func (s *Server) Subsz(opts *SubszOptions) (*Subsz, error) {
var (
subdetail bool
test bool
offset int
testSub string
filterAcc string
limit = DefaultSubListSize
)
if opts != nil {
subdetail = opts.Subscriptions
offset = opts.Offset
if offset < 0 {
offset = 0
}
limit = opts.Limit
if limit <= 0 {
limit = DefaultSubListSize
}
if opts.Test != _EMPTY_ {
testSub = opts.Test
test = true
if !IsValidLiteralSubject(testSub) {
return nil, fmt.Errorf("invalid test subject, must be valid publish subject: %s", testSub)
}
}
if opts.Account != _EMPTY_ {
filterAcc = opts.Account
}
}
slStats := &SublistStats{}
// FIXME(dlc) - Make account aware.
sz := &Subsz{s.info.ID, time.Now().UTC(), slStats, 0, offset, limit, nil}
if subdetail {
var raw [4096]*subscription
subs := raw[:0]
s.accounts.Range(func(k, v any) bool {
acc := v.(*Account)
if filterAcc != _EMPTY_ && acc.GetName() != filterAcc {
return true
}
slStats.add(acc.sl.Stats())
acc.sl.localSubs(&subs, false)
return true
})
details := make([]SubDetail, len(subs))
i := 0
// TODO(dlc) - may be inefficient and could just do normal match when total subs is large and filtering.
for _, sub := range subs {
// Check for filter
if test && !matchLiteral(testSub, string(sub.subject)) {
continue
}
if sub.client == nil {
continue
}
sub.client.mu.Lock()
details[i] = newSubDetail(sub)
sub.client.mu.Unlock()
i++
}
minoff := sz.Offset
maxoff := sz.Offset + sz.Limit
maxIndex := i
// Make sure these are sane.
if minoff > maxIndex {
minoff = maxIndex
}
if maxoff > maxIndex {
maxoff = maxIndex
}
sz.Subs = details[minoff:maxoff]
sz.Total = len(sz.Subs)
} else {
s.accounts.Range(func(k, v any) bool {
acc := v.(*Account)
if filterAcc != _EMPTY_ && acc.GetName() != filterAcc {
return true
}
slStats.add(acc.sl.Stats())
return true
})
}
return sz, nil
}
// HandleSubsz processes HTTP requests for subjects stats.
func (s *Server) HandleSubsz(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
s.httpReqStats[SubszPath]++
s.mu.Unlock()
subs, err := decodeBool(w, r, "subs")
if err != nil {
return
}
offset, err := decodeInt(w, r, "offset")
if err != nil {
return
}
limit, err := decodeInt(w, r, "limit")
if err != nil {
return
}
testSub := r.URL.Query().Get("test")
// Filtered account.
filterAcc := r.URL.Query().Get("acc")
subszOpts := &SubszOptions{
Subscriptions: subs,
Offset: offset,
Limit: limit,
Account: filterAcc,
Test: testSub,
}
st, err := s.Subsz(subszOpts)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
var b []byte
if len(st.Subs) == 0 {
b, err = json.MarshalIndent(st.SublistStats, "", " ")
} else {
b, err = json.MarshalIndent(st, "", " ")
}
if err != nil {
s.Errorf("Error marshaling response to /subscriptionsz request: %v", err)
}
// Handle response
ResponseHandler(w, r, b)
}
// HandleStacksz processes HTTP requests for getting stacks
func (s *Server) HandleStacksz(w http.ResponseWriter, r *http.Request) {
// Do not get any lock here that would prevent getting the stacks
// if we were to have a deadlock somewhere.
var defaultBuf [defaultStackBufSize]byte
size := defaultStackBufSize
buf := defaultBuf[:size]
n := 0
for {
n = runtime.Stack(buf, true)
if n < size {
break
}
size *= 2
buf = make([]byte, size)
}
// Handle response
ResponseHandler(w, r, buf[:n])
}
type IpqueueszStatusIPQ struct {
Pending int `json:"pending"`
InProgress int `json:"in_progress,omitempty"`
}
type IpqueueszStatus map[string]IpqueueszStatusIPQ
func (s *Server) Ipqueuesz(opts *IpqueueszOptions) *IpqueueszStatus {
all, qfilter := opts.All, opts.Filter
queues := IpqueueszStatus{}
s.ipQueues.Range(func(k, v any) bool {
var pending, inProgress int
name := k.(string)
queue, ok := v.(interface {
len() int
inProgress() int64
})
if ok {
pending = queue.len()
inProgress = int(queue.inProgress())
}
if !all && (pending == 0 && inProgress == 0) {
return true
} else if qfilter != _EMPTY_ && !strings.Contains(name, qfilter) {
return true
}
queues[name] = IpqueueszStatusIPQ{Pending: pending, InProgress: inProgress}
return true
})
return &queues
}
func (s *Server) HandleIPQueuesz(w http.ResponseWriter, r *http.Request) {
all, err := decodeBool(w, r, "all")
if err != nil {
return
}
qfilter := r.URL.Query().Get("queues")
queues := s.Ipqueuesz(&IpqueueszOptions{
All: all,
Filter: qfilter,
})
b, _ := json.MarshalIndent(queues, "", " ")
ResponseHandler(w, r, b)
}
// Varz will output server information on the monitoring port at /varz.
type Varz struct {
ID string `json:"server_id"`
Name string `json:"server_name"`
Version string `json:"version"`
Proto int `json:"proto"`
GitCommit string `json:"git_commit,omitempty"`
GoVersion string `json:"go"`
Host string `json:"host"`
Port int `json:"port"`
AuthRequired bool `json:"auth_required,omitempty"`
TLSRequired bool `json:"tls_required,omitempty"`
TLSVerify bool `json:"tls_verify,omitempty"`
TLSOCSPPeerVerify bool `json:"tls_ocsp_peer_verify,omitempty"`
IP string `json:"ip,omitempty"`
ClientConnectURLs []string `json:"connect_urls,omitempty"`
WSConnectURLs []string `json:"ws_connect_urls,omitempty"`
MaxConn int `json:"max_connections"`
MaxSubs int `json:"max_subscriptions,omitempty"`
PingInterval time.Duration `json:"ping_interval"`
MaxPingsOut int `json:"ping_max"`
HTTPHost string `json:"http_host"`
HTTPPort int `json:"http_port"`
HTTPBasePath string `json:"http_base_path"`
HTTPSPort int `json:"https_port"`
AuthTimeout float64 `json:"auth_timeout"`
MaxControlLine int32 `json:"max_control_line"`
MaxPayload int `json:"max_payload"`
MaxPending int64 `json:"max_pending"`
Cluster ClusterOptsVarz `json:"cluster,omitempty"`
Gateway GatewayOptsVarz `json:"gateway,omitempty"`
LeafNode LeafNodeOptsVarz `json:"leaf,omitempty"`
MQTT MQTTOptsVarz `json:"mqtt,omitempty"`
Websocket WebsocketOptsVarz `json:"websocket,omitempty"`
JetStream JetStreamVarz `json:"jetstream,omitempty"`
TLSTimeout float64 `json:"tls_timeout"`
WriteDeadline time.Duration `json:"write_deadline"`
Start time.Time `json:"start"`
Now time.Time `json:"now"`
Uptime string `json:"uptime"`
Mem int64 `json:"mem"`
Cores int `json:"cores"`
MaxProcs int `json:"gomaxprocs"`
CPU float64 `json:"cpu"`
Connections int `json:"connections"`
TotalConnections uint64 `json:"total_connections"`
Routes int `json:"routes"`
Remotes int `json:"remotes"`
Leafs int `json:"leafnodes"`
InMsgs int64 `json:"in_msgs"`
OutMsgs int64 `json:"out_msgs"`
InBytes int64 `json:"in_bytes"`
OutBytes int64 `json:"out_bytes"`
SlowConsumers int64 `json:"slow_consumers"`
Subscriptions uint32 `json:"subscriptions"`
HTTPReqStats map[string]uint64 `json:"http_req_stats"`
ConfigLoadTime time.Time `json:"config_load_time"`
Tags jwt.TagList `json:"tags,omitempty"`
TrustedOperatorsJwt []string `json:"trusted_operators_jwt,omitempty"`
TrustedOperatorsClaim []*jwt.OperatorClaims `json:"trusted_operators_claim,omitempty"`
SystemAccount string `json:"system_account,omitempty"`
PinnedAccountFail uint64 `json:"pinned_account_fails,omitempty"`
OCSPResponseCache *OCSPResponseCacheVarz `json:"ocsp_peer_cache,omitempty"`
SlowConsumersStats *SlowConsumersStats `json:"slow_consumer_stats"`
}
// JetStreamVarz contains basic runtime information about jetstream
type JetStreamVarz struct {
Config *JetStreamConfig `json:"config,omitempty"`
Stats *JetStreamStats `json:"stats,omitempty"`
Meta *MetaClusterInfo `json:"meta,omitempty"`
}
// ClusterOptsVarz contains monitoring cluster information
type ClusterOptsVarz struct {
Name string `json:"name,omitempty"`
Host string `json:"addr,omitempty"`
Port int `json:"cluster_port,omitempty"`
AuthTimeout float64 `json:"auth_timeout,omitempty"`
URLs []string `json:"urls,omitempty"`
TLSTimeout float64 `json:"tls_timeout,omitempty"`
TLSRequired bool `json:"tls_required,omitempty"`
TLSVerify bool `json:"tls_verify,omitempty"`
PoolSize int `json:"pool_size,omitempty"`
}
// GatewayOptsVarz contains monitoring gateway information
type GatewayOptsVarz struct {
Name string `json:"name,omitempty"`
Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"`
AuthTimeout float64 `json:"auth_timeout,omitempty"`
TLSTimeout float64 `json:"tls_timeout,omitempty"`
TLSRequired bool `json:"tls_required,omitempty"`
TLSVerify bool `json:"tls_verify,omitempty"`
Advertise string `json:"advertise,omitempty"`
ConnectRetries int `json:"connect_retries,omitempty"`
Gateways []RemoteGatewayOptsVarz `json:"gateways,omitempty"`
RejectUnknown bool `json:"reject_unknown,omitempty"` // config got renamed to reject_unknown_cluster
}
// RemoteGatewayOptsVarz contains monitoring remote gateway information
type RemoteGatewayOptsVarz struct {
Name string `json:"name"`
TLSTimeout float64 `json:"tls_timeout,omitempty"`
URLs []string `json:"urls,omitempty"`
}
// LeafNodeOptsVarz contains monitoring leaf node information
type LeafNodeOptsVarz struct {
Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"`
AuthTimeout float64 `json:"auth_timeout,omitempty"`
TLSTimeout float64 `json:"tls_timeout,omitempty"`
TLSRequired bool `json:"tls_required,omitempty"`
TLSVerify bool `json:"tls_verify,omitempty"`
Remotes []RemoteLeafOptsVarz `json:"remotes,omitempty"`
TLSOCSPPeerVerify bool `json:"tls_ocsp_peer_verify,omitempty"`
}
// DenyRules Contains lists of subjects not allowed to be imported/exported
type DenyRules struct {
Exports []string `json:"exports,omitempty"`
Imports []string `json:"imports,omitempty"`
}
// RemoteLeafOptsVarz contains monitoring remote leaf node information
type RemoteLeafOptsVarz struct {
LocalAccount string `json:"local_account,omitempty"`
TLSTimeout float64 `json:"tls_timeout,omitempty"`
URLs []string `json:"urls,omitempty"`
Deny *DenyRules `json:"deny,omitempty"`
TLSOCSPPeerVerify bool `json:"tls_ocsp_peer_verify,omitempty"`
}
// MQTTOptsVarz contains monitoring MQTT information
type MQTTOptsVarz struct {
Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"`
NoAuthUser string `json:"no_auth_user,omitempty"`
AuthTimeout float64 `json:"auth_timeout,omitempty"`
TLSMap bool `json:"tls_map,omitempty"`
TLSTimeout float64 `json:"tls_timeout,omitempty"`
TLSPinnedCerts []string `json:"tls_pinned_certs,omitempty"`
JsDomain string `json:"js_domain,omitempty"`
AckWait time.Duration `json:"ack_wait,omitempty"`
MaxAckPending uint16 `json:"max_ack_pending,omitempty"`
TLSOCSPPeerVerify bool `json:"tls_ocsp_peer_verify,omitempty"`
}
// WebsocketOptsVarz contains monitoring websocket information
type WebsocketOptsVarz struct {
Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"`
Advertise string `json:"advertise,omitempty"`
NoAuthUser string `json:"no_auth_user,omitempty"`
JWTCookie string `json:"jwt_cookie,omitempty"`
HandshakeTimeout time.Duration `json:"handshake_timeout,omitempty"`
AuthTimeout float64 `json:"auth_timeout,omitempty"`
NoTLS bool `json:"no_tls,omitempty"`
TLSMap bool `json:"tls_map,omitempty"`
TLSPinnedCerts []string `json:"tls_pinned_certs,omitempty"`
SameOrigin bool `json:"same_origin,omitempty"`
AllowedOrigins []string `json:"allowed_origins,omitempty"`
Compression bool `json:"compression,omitempty"`
TLSOCSPPeerVerify bool `json:"tls_ocsp_peer_verify,omitempty"`
}
// OCSPResponseCacheVarz contains OCSP response cache information
type OCSPResponseCacheVarz struct {
Type string `json:"cache_type,omitempty"`
Hits int64 `json:"cache_hits,omitempty"`
Misses int64 `json:"cache_misses,omitempty"`
Responses int64 `json:"cached_responses,omitempty"`
Revokes int64 `json:"cached_revoked_responses,omitempty"`
Goods int64 `json:"cached_good_responses,omitempty"`
Unknowns int64 `json:"cached_unknown_responses,omitempty"`
}
// VarzOptions are the options passed to Varz().
// Currently, there are no options defined.
type VarzOptions struct{}
// SlowConsumersStats contains information about the slow consumers from different type of connections.
type SlowConsumersStats struct {
Clients uint64 `json:"clients"`
Routes uint64 `json:"routes"`
Gateways uint64 `json:"gateways"`
Leafs uint64 `json:"leafs"`
}
func myUptime(d time.Duration) string {
// Just use total seconds for uptime, and display days / years
tsecs := d / time.Second
tmins := tsecs / 60
thrs := tmins / 60
tdays := thrs / 24
tyrs := tdays / 365
if tyrs > 0 {
return fmt.Sprintf("%dy%dd%dh%dm%ds", tyrs, tdays%365, thrs%24, tmins%60, tsecs%60)
}
if tdays > 0 {
return fmt.Sprintf("%dd%dh%dm%ds", tdays, thrs%24, tmins%60, tsecs%60)
}
if thrs > 0 {
return fmt.Sprintf("%dh%dm%ds", thrs, tmins%60, tsecs%60)
}
if tmins > 0 {
return fmt.Sprintf("%dm%ds", tmins, tsecs%60)
}
return fmt.Sprintf("%ds", tsecs)
}
// HandleRoot will show basic info and links to others handlers.
func (s *Server) HandleRoot(w http.ResponseWriter, r *http.Request) {
// This feels dumb to me, but is required: https://code.google.com/p/go/issues/detail?id=4799
if r.URL.Path != s.httpBasePath {
http.NotFound(w, r)
return
}
s.mu.Lock()
s.httpReqStats[RootPath]++
s.mu.Unlock()
// Calculate source url. If git set go directly to that tag, otherwise just main.
var srcUrl string
if gitCommit == _EMPTY_ {
srcUrl = "https://github.com/nats-io/nats-server"
} else if serverVersion != _EMPTY_ {
srcUrl = fmt.Sprintf("https://github.com/nats-io/nats-server/tree/%s", serverVersion)
} else {
srcUrl = fmt.Sprintf("https://github.com/nats-io/nats-server/tree/%s", gitCommit)
}
fmt.Fprintf(w, `<html lang="en">
<head>
<link rel="shortcut icon" href="https://nats.io/favicon.ico">
<style type="text/css">
body { font-family: ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif; font-size: 18; font-weight: light-bold; margin-left: 32px }
a { display:block; margin-left: 7px; padding-bottom: 6px; color: rgb(72 72 92); text-decoration: none }
a:hover { font-weight: 600; color: rgb(59 50 202) }
a.help { display:inline; font-weight: 600; color: rgb(59 50 202); font-size: 20}
a.last { padding-bottom: 16px }
a.version { font-size: 14; font-weight: 400; width: 312px; text-align: right; margin-top: -2rem }
a.version:hover { color: rgb(22 22 32) }
</style>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg" role="img" width="325" height="110" viewBox="-4.14 -3.89 436.28 119.03"><style>.st1{fill:#fff}.st2{fill:#34a574}</style><path fill="#27aae1" d="M4.3 84.6h42.2L70.7 107V84.6H103v-80H4.3v80zm15.9-61.3h18.5l35.6 33.2V23.3h11.8v42.9H68.2L32 32.4v33.8H20.2V23.3z"/><path d="M32 32.4l36.2 33.8h17.9V23.3H74.3v33.2L38.7 23.3H20.2v42.9H32z" class="st1"/><path d="M159.8 30.7L147 49h25.6z" class="st2"/><path d="M111.3 84.6H210v-80h-98.7v80zm41-61.5H168l30.8 43.2h-14.1l-5.8-8.3h-38.1l-5.8 8.3h-13.5l30.8-43.2z" class="st2"/><path d="M140.8 57.9h38.1l5.8 8.3h14.1L168 23.1h-15.7l-30.8 43.2H135l5.8-8.4zm19-27.2L172.6 49H147l12.8-18.3z" class="st1"/><path fill="#375c93" d="M218.3 84.6H317v-80h-98.7v80zm15.5-61.3h66.7V33h-27.2v33.2h-12.2V33h-27.3v-9.7z"/><path d="M261.1 66.2h12.2V33h27.2v-9.7h-66.7V33h27.3z" class="st1"/><path fill="#8dc63f" d="M325.3 4.6v80H424v-80h-98.7zm76.5 56.7c-3.2 3.2-10.2 5.7-26.8 5.7-12.3 0-24.1-1.9-30.7-4.7v-10c6.3 2.8 20.1 5.5 30.7 5.5 9.3 0 15.8-.3 17.5-2.1.6-.6.7-1.3.7-2 0-.8-.2-1.3-.7-1.8-1-1-2.6-1.7-17.4-2.1-15.7-.4-23.4-2-27-5.6-1.7-1.7-2.6-4.4-2.6-7.5 0-3.3.6-6.2 3.3-8.9 3.6-3.6 10.7-5.3 25.1-5.3 10.8 0 21.6 1.7 27.3 4v10.1c-6.5-2.8-17.8-4.8-27.2-4.8-10.4 0-14.8.6-16.2 2-.5.5-.8 1.1-.8 1.9 0 .9.2 1.5.7 2 1.3 1.3 6.1 1.7 17.3 1.9 16.4.4 23.5 1.8 27 5.2 1.8 1.8 2.8 4.7 2.8 7.7.1 3.2-.6 6.4-3 8.8z"/><path d="M375.2 39.5c-11.2-.2-16-.6-17.3-1.9-.5-.5-.7-1.1-.7-2 0-.8.3-1.4.8-1.9 1.3-1.3 5.8-2 16.2-2 9.4 0 20.7 2 27.2 4.8v-10c-5.7-2.3-16.6-4-27.3-4-14.5 0-21.6 1.8-25.1 5.3-2.7 2.7-3.3 5.6-3.3 8.9 0 3.1 1 5.8 2.6 7.5 3.6 3.6 11.3 5.2 27 5.6 14.8.4 16.4 1.1 17.4 2.1.5.5.7 1 .7 1.8 0 .7-.1 1.3-.7 2-1.8 1.8-8.3 2.1-17.5 2.1-10.6 0-24.3-2.6-30.7-5.5v10.1c6.6 2.8 18.4 4.7 30.7 4.7 16.6 0 23.6-2.5 26.8-5.7 2.4-2.4 3.1-5.6 3.1-8.9 0-3.1-1-5.9-2.8-7.7-3.6-3.5-10.7-4.9-27.1-5.3z" class="st1"/></svg>
<a href=%s class='version'>v%s</a>
</div>
<br/>
<a href=.%s>General</a>
<a href=.%s>JetStream</a>
<a href=.%s>Connections</a>
<a href=.%s>Accounts</a>
<a href=.%s>Account Stats</a>
<a href=.%s>Subscriptions</a>
<a href=.%s>Routes</a>
<a href=.%s>LeafNodes</a>
<a href=.%s>Gateways</a>
<a href=.%s>Raft Groups</a>
<a href=.%s class=last>Health Probe</a>
<a href=https://docs.nats.io/running-a-nats-service/nats_admin/monitoring class="help">Help</a>
</body>
</html>`,
srcUrl,
VERSION,
s.basePath(VarzPath),
s.basePath(JszPath),
s.basePath(ConnzPath),
s.basePath(AccountzPath),
s.basePath(AccountStatzPath),
s.basePath(SubszPath),
s.basePath(RoutezPath),
s.basePath(LeafzPath),
s.basePath(GatewayzPath),
s.basePath(RaftzPath),
s.basePath(HealthzPath),
)
}
func (s *Server) updateJszVarz(js *jetStream, v *JetStreamVarz, doConfig bool) {
if doConfig {
js.mu.RLock()
// We want to snapshot the config since it will then be available outside
// of the js lock. So make a copy first, then point to this copy.
cfg := js.config
v.Config = &cfg
js.mu.RUnlock()
}
v.Stats = js.usageStats()
if mg := js.getMetaGroup(); mg != nil {
if ci := s.raftNodeToClusterInfo(mg); ci != nil {
v.Meta = &MetaClusterInfo{Name: ci.Name, Leader: ci.Leader, Peer: getHash(ci.Leader), Size: mg.ClusterSize()}
if ci.Leader == s.info.Name {
v.Meta.Replicas = ci.Replicas
}
if ipq := s.jsAPIRoutedReqs; ipq != nil {
v.Meta.Pending = ipq.len()
}
}
}
}
// Varz returns a Varz struct containing the server information.
func (s *Server) Varz(varzOpts *VarzOptions) (*Varz, error) {
var rss, vss int64
var pcpu float64
// We want to do that outside of the lock.
pse.ProcUsage(&pcpu, &rss, &vss)
s.mu.RLock()
// We need to create a new instance of Varz (with no reference
// whatsoever to anything stored in the server) since the user
// has access to the returned value.
v := s.createVarz(pcpu, rss)
s.mu.RUnlock()
if js := s.getJetStream(); js != nil {
s.updateJszVarz(js, &v.JetStream, true)
}
return v, nil
}
// Returns a Varz instance.
// Server lock is held on entry.
func (s *Server) createVarz(pcpu float64, rss int64) *Varz {
info := s.info
opts := s.getOpts()
c := &opts.Cluster
gw := &opts.Gateway
ln := &opts.LeafNode
mqtt := &opts.MQTT
ws := &opts.Websocket
clustTlsReq := c.TLSConfig != nil
gatewayTlsReq := gw.TLSConfig != nil
leafTlsReq := ln.TLSConfig != nil
leafTlsVerify := leafTlsReq && ln.TLSConfig.ClientAuth == tls.RequireAndVerifyClientCert
leafTlsOCSPPeerVerify := s.ocspPeerVerify && leafTlsReq && ln.tlsConfigOpts.OCSPPeerConfig != nil && ln.tlsConfigOpts.OCSPPeerConfig.Verify
mqttTlsOCSPPeerVerify := s.ocspPeerVerify && mqtt.TLSConfig != nil && mqtt.tlsConfigOpts.OCSPPeerConfig != nil && mqtt.tlsConfigOpts.OCSPPeerConfig.Verify
wsTlsOCSPPeerVerify := s.ocspPeerVerify && ws.TLSConfig != nil && ws.tlsConfigOpts.OCSPPeerConfig != nil && ws.tlsConfigOpts.OCSPPeerConfig.Verify
varz := &Varz{
ID: info.ID,
Version: info.Version,
Proto: info.Proto,
GitCommit: info.GitCommit,
GoVersion: info.GoVersion,
Name: info.Name,
Host: info.Host,
Port: info.Port,
IP: info.IP,
HTTPHost: opts.HTTPHost,
HTTPPort: opts.HTTPPort,
HTTPBasePath: opts.HTTPBasePath,
HTTPSPort: opts.HTTPSPort,
Cluster: ClusterOptsVarz{
Name: info.Cluster,
Host: c.Host,
Port: c.Port,
AuthTimeout: c.AuthTimeout,
TLSTimeout: c.TLSTimeout,
TLSRequired: clustTlsReq,
TLSVerify: clustTlsReq,
PoolSize: opts.Cluster.PoolSize,
},
Gateway: GatewayOptsVarz{
Name: gw.Name,
Host: gw.Host,
Port: gw.Port,
AuthTimeout: gw.AuthTimeout,
TLSTimeout: gw.TLSTimeout,
TLSRequired: gatewayTlsReq,
TLSVerify: gatewayTlsReq,
Advertise: gw.Advertise,
ConnectRetries: gw.ConnectRetries,
Gateways: []RemoteGatewayOptsVarz{},
RejectUnknown: gw.RejectUnknown,
},
LeafNode: LeafNodeOptsVarz{
Host: ln.Host,
Port: ln.Port,
AuthTimeout: ln.AuthTimeout,
TLSTimeout: ln.TLSTimeout,
TLSRequired: leafTlsReq,
TLSVerify: leafTlsVerify,
TLSOCSPPeerVerify: leafTlsOCSPPeerVerify,
Remotes: []RemoteLeafOptsVarz{},
},
MQTT: MQTTOptsVarz{
Host: mqtt.Host,
Port: mqtt.Port,
NoAuthUser: mqtt.NoAuthUser,
AuthTimeout: mqtt.AuthTimeout,
TLSMap: mqtt.TLSMap,
TLSTimeout: mqtt.TLSTimeout,
JsDomain: mqtt.JsDomain,
AckWait: mqtt.AckWait,
MaxAckPending: mqtt.MaxAckPending,
TLSOCSPPeerVerify: mqttTlsOCSPPeerVerify,
},
Websocket: WebsocketOptsVarz{
Host: ws.Host,
Port: ws.Port,
Advertise: ws.Advertise,
NoAuthUser: ws.NoAuthUser,
JWTCookie: ws.JWTCookie,
AuthTimeout: ws.AuthTimeout,
NoTLS: ws.NoTLS,
TLSMap: ws.TLSMap,
SameOrigin: ws.SameOrigin,
AllowedOrigins: copyStrings(ws.AllowedOrigins),
Compression: ws.Compression,
HandshakeTimeout: ws.HandshakeTimeout,
TLSOCSPPeerVerify: wsTlsOCSPPeerVerify,
},
Start: s.start.UTC(),
MaxSubs: opts.MaxSubs,
Cores: runtime.NumCPU(),
MaxProcs: runtime.GOMAXPROCS(0),
Tags: opts.Tags,
TrustedOperatorsJwt: opts.operatorJWT,
TrustedOperatorsClaim: opts.TrustedOperators,
}
if len(opts.Routes) > 0 {
varz.Cluster.URLs = urlsToStrings(opts.Routes)
}
if l := len(gw.Gateways); l > 0 {
rgwa := make([]RemoteGatewayOptsVarz, l)
for i, r := range gw.Gateways {
rgwa[i] = RemoteGatewayOptsVarz{
Name: r.Name,
TLSTimeout: r.TLSTimeout,
}
}
varz.Gateway.Gateways = rgwa
}
if l := len(ln.Remotes); l > 0 {
rlna := make([]RemoteLeafOptsVarz, l)
for i, r := range ln.Remotes {
var deny *DenyRules
if len(r.DenyImports) > 0 || len(r.DenyExports) > 0 {
deny = &DenyRules{
Imports: r.DenyImports,
Exports: r.DenyExports,
}
}
remoteTlsOCSPPeerVerify := s.ocspPeerVerify && r.tlsConfigOpts != nil && r.tlsConfigOpts.OCSPPeerConfig != nil && r.tlsConfigOpts.OCSPPeerConfig.Verify
rlna[i] = RemoteLeafOptsVarz{
LocalAccount: r.LocalAccount,
URLs: urlsToStrings(r.URLs),
TLSTimeout: r.TLSTimeout,
Deny: deny,
TLSOCSPPeerVerify: remoteTlsOCSPPeerVerify,
}
}
varz.LeafNode.Remotes = rlna
}
// Finish setting it up with fields that can be updated during
// configuration reload and runtime.
s.updateVarzConfigReloadableFields(varz)
s.updateVarzRuntimeFields(varz, true, pcpu, rss)
return varz
}
func urlsToStrings(urls []*url.URL) []string {
sURLs := make([]string, len(urls))
for i, u := range urls {
sURLs[i] = u.Host
}
return sURLs
}
// Invoked during configuration reload once options have possibly be changed
// and config load time has been set. If s.varz has not been initialized yet
// (because no pooling of /varz has been made), this function does nothing.
// Server lock is held on entry.
func (s *Server) updateVarzConfigReloadableFields(v *Varz) {
if v == nil {
return
}
opts := s.getOpts()
info := &s.info
v.AuthRequired = info.AuthRequired
v.TLSRequired = info.TLSRequired
v.TLSVerify = info.TLSVerify
v.MaxConn = opts.MaxConn
v.PingInterval = opts.PingInterval
v.MaxPingsOut = opts.MaxPingsOut
v.AuthTimeout = opts.AuthTimeout
v.MaxControlLine = opts.MaxControlLine
v.MaxPayload = int(opts.MaxPayload)
v.MaxPending = opts.MaxPending
v.TLSTimeout = opts.TLSTimeout
v.WriteDeadline = opts.WriteDeadline
v.ConfigLoadTime = s.configTime.UTC()
// Update route URLs if applicable
if s.varzUpdateRouteURLs {
v.Cluster.URLs = urlsToStrings(opts.Routes)
s.varzUpdateRouteURLs = false
}
if s.sys != nil && s.sys.account != nil {
v.SystemAccount = s.sys.account.GetName()
}
v.MQTT.TLSPinnedCerts = getPinnedCertsAsSlice(opts.MQTT.TLSPinnedCerts)
v.Websocket.TLSPinnedCerts = getPinnedCertsAsSlice(opts.Websocket.TLSPinnedCerts)
v.TLSOCSPPeerVerify = s.ocspPeerVerify && v.TLSRequired && s.opts.tlsConfigOpts != nil && s.opts.tlsConfigOpts.OCSPPeerConfig != nil && s.opts.tlsConfigOpts.OCSPPeerConfig.Verify
}
func getPinnedCertsAsSlice(certs PinnedCertSet) []string {
if len(certs) == 0 {
return nil
}
res := make([]string, 0, len(certs))
for cn := range certs {
res = append(res, cn)
}
return res
}
// Updates the runtime Varz fields, that is, fields that change during
// runtime and that should be updated any time Varz() or polling of /varz
// is done.
// Server lock is held on entry.
func (s *Server) updateVarzRuntimeFields(v *Varz, forceUpdate bool, pcpu float64, rss int64) {
v.Now = time.Now().UTC()
v.Uptime = myUptime(time.Since(s.start))
v.Mem = rss
v.CPU = pcpu
if l := len(s.info.ClientConnectURLs); l > 0 {
v.ClientConnectURLs = append([]string(nil), s.info.ClientConnectURLs...)
}
if l := len(s.info.WSConnectURLs); l > 0 {
v.WSConnectURLs = append([]string(nil), s.info.WSConnectURLs...)
}
v.Connections = len(s.clients)
v.TotalConnections = s.totalClients
v.Routes = s.numRoutes()
v.Remotes = s.numRemotes()
v.Leafs = len(s.leafs)
v.InMsgs = atomic.LoadInt64(&s.inMsgs)
v.InBytes = atomic.LoadInt64(&s.inBytes)
v.OutMsgs = atomic.LoadInt64(&s.outMsgs)
v.OutBytes = atomic.LoadInt64(&s.outBytes)
v.SlowConsumers = atomic.LoadInt64(&s.slowConsumers)
v.SlowConsumersStats = &SlowConsumersStats{
Clients: s.NumSlowConsumersClients(),
Routes: s.NumSlowConsumersRoutes(),
Gateways: s.NumSlowConsumersGateways(),
Leafs: s.NumSlowConsumersLeafs(),
}
v.PinnedAccountFail = atomic.LoadUint64(&s.pinnedAccFail)
// Make sure to reset in case we are re-using.
v.Subscriptions = 0
s.accounts.Range(func(k, val any) bool {
acc := val.(*Account)
v.Subscriptions += acc.sl.Count()
return true
})
v.HTTPReqStats = make(map[string]uint64, len(s.httpReqStats))
for key, val := range s.httpReqStats {
v.HTTPReqStats[key] = val
}
// Update Gateway remote urls if applicable
gw := s.gateway
gw.RLock()
if gw.enabled {
for i := 0; i < len(v.Gateway.Gateways); i++ {
g := &v.Gateway.Gateways[i]
rgw := gw.remotes[g.Name]
if rgw != nil {
rgw.RLock()
// forceUpdate is needed if user calls Varz() programmatically,
// since we need to create a new instance every time and the
// gateway's varzUpdateURLs may have been set to false after
// a web /varz inspection.
if forceUpdate || rgw.varzUpdateURLs {
// Make reuse of backend array
g.URLs = g.URLs[:0]
// rgw.urls is a map[string]*url.URL where the key is
// already in the right format (host:port, without any
// user info present).
for u := range rgw.urls {
g.URLs = append(g.URLs, u)
}
rgw.varzUpdateURLs = false
}
rgw.RUnlock()
} else if g.Name == gw.name && len(gw.ownCfgURLs) > 0 {
// This is a remote that correspond to this very same server.
// We report the URLs that were configured (if any).
// Since we don't support changes to the gateway configuration
// at this time, we could do this only if g.URLs has not been already
// set, but let's do it regardless in case we add support for
// gateway config reload.
g.URLs = g.URLs[:0]
g.URLs = append(g.URLs, gw.ownCfgURLs...)
}
}
}
gw.RUnlock()
if s.ocsprc != nil && s.ocsprc.Type() != "none" {
stats := s.ocsprc.Stats()
if stats != nil {
v.OCSPResponseCache = &OCSPResponseCacheVarz{
s.ocsprc.Type(),
stats.Hits,
stats.Misses,
stats.Responses,
stats.Revokes,
stats.Goods,
stats.Unknowns,
}
}
}
}
// HandleVarz will process HTTP requests for server information.
func (s *Server) HandleVarz(w http.ResponseWriter, r *http.Request) {
var rss, vss int64
var pcpu float64
// We want to do that outside of the lock.
pse.ProcUsage(&pcpu, &rss, &vss)
// In response to http requests, we want to minimize mem copies
// so we use an object stored in the server. Creating/collecting
// server metrics is done under server lock, but we don't want
// to marshal under that lock. Still, we need to prevent concurrent
// http requests to /varz to update s.varz while marshal is
// happening, so we need a new lock that serialize those http
// requests and include marshaling.
s.varzMu.Lock()
// Use server lock to create/update the server's varz object.
s.mu.Lock()
var created bool
s.httpReqStats[VarzPath]++
if s.varz == nil {
s.varz = s.createVarz(pcpu, rss)
created = true
} else {
s.updateVarzRuntimeFields(s.varz, false, pcpu, rss)
}
s.mu.Unlock()
// Since locking is jetStream -> Server, need to update jetstream
// varz outside of server lock.
if js := s.getJetStream(); js != nil {
var v JetStreamVarz
// Work on stack variable
s.updateJszVarz(js, &v, created)
// Now update server's varz
s.mu.RLock()
sv := &s.varz.JetStream
if created {
sv.Config = v.Config
}
sv.Stats = v.Stats
sv.Meta = v.Meta
s.mu.RUnlock()
}
// Do the marshaling outside of server lock, but under varzMu lock.
b, err := json.MarshalIndent(s.varz, "", " ")
s.varzMu.Unlock()
if err != nil {
s.Errorf("Error marshaling response to /varz request: %v", err)
}
// Handle response
ResponseHandler(w, r, b)
}
// GatewayzOptions are the options passed to Gatewayz()
type GatewayzOptions struct {
// Name will output only remote gateways with this name
Name string `json:"name"`
// Accounts indicates if accounts with its interest should be included in the results.
Accounts bool `json:"accounts"`
// AccountName will limit the list of accounts to that account name (makes Accounts implicit)
AccountName string `json:"account_name"`
// AccountSubscriptions indicates if subscriptions should be included in the results.
// Note: This is used only if `Accounts` or `AccountName` are specified.
AccountSubscriptions bool `json:"subscriptions"`
// AccountSubscriptionsDetail indicates if subscription details should be included in the results.
// Note: This is used only if `Accounts` or `AccountName` are specified.
AccountSubscriptionsDetail bool `json:"subscriptions_detail"`
}
// Gatewayz represents detailed information on Gateways
type Gatewayz struct {
ID string `json:"server_id"`
Now time.Time `json:"now"`
Name string `json:"name,omitempty"`
Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"`
OutboundGateways map[string]*RemoteGatewayz `json:"outbound_gateways"`
InboundGateways map[string][]*RemoteGatewayz `json:"inbound_gateways"`
}
// RemoteGatewayz represents information about an outbound connection to a gateway
type RemoteGatewayz struct {
IsConfigured bool `json:"configured"`
Connection *ConnInfo `json:"connection,omitempty"`
Accounts []*AccountGatewayz `json:"accounts,omitempty"`
}
// AccountGatewayz represents interest mode for this account
type AccountGatewayz struct {
Name string `json:"name"`
InterestMode string `json:"interest_mode"`
NoInterestCount int `json:"no_interest_count,omitempty"`
InterestOnlyThreshold int `json:"interest_only_threshold,omitempty"`
TotalSubscriptions int `json:"num_subs,omitempty"`
NumQueueSubscriptions int `json:"num_queue_subs,omitempty"`
Subs []string `json:"subscriptions_list,omitempty"`
SubsDetail []SubDetail `json:"subscriptions_list_detail,omitempty"`
}
// Gatewayz returns a Gatewayz struct containing information about gateways.
func (s *Server) Gatewayz(opts *GatewayzOptions) (*Gatewayz, error) {
srvID := s.ID()
now := time.Now().UTC()
gw := s.gateway
gw.RLock()
if !gw.enabled || gw.info == nil {
gw.RUnlock()
gwz := &Gatewayz{
ID: srvID,
Now: now,
OutboundGateways: map[string]*RemoteGatewayz{},
InboundGateways: map[string][]*RemoteGatewayz{},
}
return gwz, nil
}
// Here gateways are enabled, so fill up more.
gwz := &Gatewayz{
ID: srvID,
Now: now,
Name: gw.name,
Host: gw.info.Host,
Port: gw.info.Port,
}
gw.RUnlock()
gwz.OutboundGateways = s.createOutboundsRemoteGatewayz(opts, now)
gwz.InboundGateways = s.createInboundsRemoteGatewayz(opts, now)
return gwz, nil
}
// Based on give options struct, returns if there is a filtered
// Gateway Name and if we should do report Accounts.
// Note that if Accounts is false but AccountName is not empty,
// then Accounts is implicitly set to true.
func getMonitorGWOptions(opts *GatewayzOptions) (string, bool) {
var name string
var accs bool
if opts != nil {
if opts.Name != _EMPTY_ {
name = opts.Name
}
accs = opts.Accounts
if !accs && opts.AccountName != _EMPTY_ {
accs = true
}
}
return name, accs
}
// Returns a map of gateways outbound connections.
// Based on options, will include a single or all gateways,
// with no/single/or all accounts interest information.
func (s *Server) createOutboundsRemoteGatewayz(opts *GatewayzOptions, now time.Time) map[string]*RemoteGatewayz {
targetGWName, doAccs := getMonitorGWOptions(opts)
if targetGWName != _EMPTY_ {
c := s.getOutboundGatewayConnection(targetGWName)
if c == nil {
return nil
}
outbounds := make(map[string]*RemoteGatewayz, 1)
_, rgw := createOutboundRemoteGatewayz(c, opts, now, doAccs)
outbounds[targetGWName] = rgw
return outbounds
}
var connsa [16]*client
var conns = connsa[:0]
s.getOutboundGatewayConnections(&conns)
outbounds := make(map[string]*RemoteGatewayz, len(conns))
for _, c := range conns {
name, rgw := createOutboundRemoteGatewayz(c, opts, now, doAccs)
if rgw != nil {
outbounds[name] = rgw
}
}
return outbounds
}
// Returns a RemoteGatewayz for a given outbound gw connection
func createOutboundRemoteGatewayz(c *client, opts *GatewayzOptions, now time.Time, doAccs bool) (string, *RemoteGatewayz) {
var name string
var rgw *RemoteGatewayz
c.mu.Lock()
if c.gw != nil {
rgw = &RemoteGatewayz{}
if doAccs {
rgw.Accounts = createOutboundAccountsGatewayz(opts, c.gw)
}
if c.gw.cfg != nil {
rgw.IsConfigured = !c.gw.cfg.isImplicit()
}
rgw.Connection = &ConnInfo{}
rgw.Connection.fill(c, c.nc, now, false)
name = c.gw.name
}
c.mu.Unlock()
return name, rgw
}
// Returns the list of accounts for this outbound gateway connection.
// Based on the options, it will be a single or all accounts for
// this outbound.
func createOutboundAccountsGatewayz(opts *GatewayzOptions, gw *gateway) []*AccountGatewayz {
if gw.outsim == nil {
return nil
}
var accName string
if opts != nil {
accName = opts.AccountName
}
if accName != _EMPTY_ {
ei, ok := gw.outsim.Load(accName)
if !ok {
return nil
}
a := createAccountOutboundGatewayz(opts, accName, ei)
return []*AccountGatewayz{a}
}
accs := make([]*AccountGatewayz, 0, 4)
gw.outsim.Range(func(k, v any) bool {
name := k.(string)
a := createAccountOutboundGatewayz(opts, name, v)
accs = append(accs, a)
return true
})
return accs
}
// Returns an AccountGatewayz for this gateway outbound connection
func createAccountOutboundGatewayz(opts *GatewayzOptions, name string, ei any) *AccountGatewayz {
a := &AccountGatewayz{
Name: name,
InterestOnlyThreshold: gatewayMaxRUnsubBeforeSwitch,
}
if ei != nil {
e := ei.(*outsie)
e.RLock()
a.InterestMode = e.mode.String()
a.NoInterestCount = len(e.ni)
a.NumQueueSubscriptions = e.qsubs
a.TotalSubscriptions = int(e.sl.Count())
if opts.AccountSubscriptions || opts.AccountSubscriptionsDetail {
var subsa [4096]*subscription
subs := subsa[:0]
e.sl.All(&subs)
if opts.AccountSubscriptions {
a.Subs = make([]string, 0, len(subs))
} else {
a.SubsDetail = make([]SubDetail, 0, len(subs))
}
for _, sub := range subs {
if opts.AccountSubscriptions {
a.Subs = append(a.Subs, string(sub.subject))
} else {
a.SubsDetail = append(a.SubsDetail, newClientSubDetail(sub))
}
}
}
e.RUnlock()
} else {
a.InterestMode = Optimistic.String()
}
return a
}
// Returns a map of gateways inbound connections.
// Each entry is an array of RemoteGatewayz since a given server
// may have more than one inbound from the same remote gateway.
// Based on options, will include a single or all gateways,
// with no/single/or all accounts interest information.
func (s *Server) createInboundsRemoteGatewayz(opts *GatewayzOptions, now time.Time) map[string][]*RemoteGatewayz {
targetGWName, doAccs := getMonitorGWOptions(opts)
var connsa [16]*client
var conns = connsa[:0]
s.getInboundGatewayConnections(&conns)
m := make(map[string][]*RemoteGatewayz)
for _, c := range conns {
c.mu.Lock()
if c.gw != nil && (targetGWName == _EMPTY_ || targetGWName == c.gw.name) {
igws := m[c.gw.name]
if igws == nil {
igws = make([]*RemoteGatewayz, 0, 2)
}
rgw := &RemoteGatewayz{}
if doAccs {
rgw.Accounts = createInboundAccountsGatewayz(opts, c.gw)
}
rgw.Connection = &ConnInfo{}
rgw.Connection.fill(c, c.nc, now, false)
igws = append(igws, rgw)
m[c.gw.name] = igws
}
c.mu.Unlock()
}
return m
}
// Returns the list of accounts for this inbound gateway connection.
// Based on the options, it will be a single or all accounts for
// this inbound.
func createInboundAccountsGatewayz(opts *GatewayzOptions, gw *gateway) []*AccountGatewayz {
if gw.insim == nil {
return nil
}
var accName string
if opts != nil {
accName = opts.AccountName
}
if accName != _EMPTY_ {
e, ok := gw.insim[accName]
if !ok {
return nil
}
a := createInboundAccountGatewayz(accName, e)
return []*AccountGatewayz{a}
}
accs := make([]*AccountGatewayz, 0, 4)
for name, e := range gw.insim {
a := createInboundAccountGatewayz(name, e)
accs = append(accs, a)
}
return accs
}
// Returns an AccountGatewayz for this gateway inbound connection
func createInboundAccountGatewayz(name string, e *insie) *AccountGatewayz {
a := &AccountGatewayz{
Name: name,
InterestOnlyThreshold: gatewayMaxRUnsubBeforeSwitch,
}
if e != nil {
a.InterestMode = e.mode.String()
a.NoInterestCount = len(e.ni)
} else {
a.InterestMode = Optimistic.String()
}
return a
}
// HandleGatewayz process HTTP requests for route information.
func (s *Server) HandleGatewayz(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
s.httpReqStats[GatewayzPath]++
s.mu.Unlock()
subs, subsDet, err := decodeSubs(w, r)
if err != nil {
return
}
accs, err := decodeBool(w, r, "accs")
if err != nil {
return
}
gwName := r.URL.Query().Get("gw_name")
accName := r.URL.Query().Get("acc_name")
if accName != _EMPTY_ {
accs = true
}
opts := &GatewayzOptions{
Name: gwName,
Accounts: accs,
AccountName: accName,
AccountSubscriptions: subs,
AccountSubscriptionsDetail: subsDet,
}
gw, err := s.Gatewayz(opts)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
b, err := json.MarshalIndent(gw, "", " ")
if err != nil {
s.Errorf("Error marshaling response to /gatewayz request: %v", err)
}
// Handle response
ResponseHandler(w, r, b)
}
// Leafz represents detailed information on Leafnodes.
type Leafz struct {
ID string `json:"server_id"`
Now time.Time `json:"now"`
NumLeafs int `json:"leafnodes"`
Leafs []*LeafInfo `json:"leafs"`
}
// LeafzOptions are options passed to Leafz
type LeafzOptions struct {
// Subscriptions indicates that Leafz will return a leafnode's subscriptions
Subscriptions bool `json:"subscriptions"`
Account string `json:"account"`
}
// LeafInfo has detailed information on each remote leafnode connection.
type LeafInfo struct {
Name string `json:"name"`
IsSpoke bool `json:"is_spoke"`
Account string `json:"account"`
IP string `json:"ip"`
Port int `json:"port"`
RTT string `json:"rtt,omitempty"`
InMsgs int64 `json:"in_msgs"`
OutMsgs int64 `json:"out_msgs"`
InBytes int64 `json:"in_bytes"`
OutBytes int64 `json:"out_bytes"`
NumSubs uint32 `json:"subscriptions"`
Subs []string `json:"subscriptions_list,omitempty"`
Compression string `json:"compression,omitempty"`
}
// Leafz returns a Leafz structure containing information about leafnodes.
func (s *Server) Leafz(opts *LeafzOptions) (*Leafz, error) {
// Grab leafnodes
var lconns []*client
s.mu.Lock()
if len(s.leafs) > 0 {
lconns = make([]*client, 0, len(s.leafs))
for _, ln := range s.leafs {
if opts != nil && opts.Account != _EMPTY_ {
ln.mu.Lock()
ok := ln.acc.Name == opts.Account
ln.mu.Unlock()
if !ok {
continue
}
}
lconns = append(lconns, ln)
}
}
s.mu.Unlock()
leafnodes := make([]*LeafInfo, 0, len(lconns))
if len(lconns) > 0 {
for _, ln := range lconns {
ln.mu.Lock()
lni := &LeafInfo{
Name: ln.leaf.remoteServer,
IsSpoke: ln.isSpokeLeafNode(),
Account: ln.acc.Name,
IP: ln.host,
Port: int(ln.port),
RTT: ln.getRTT().String(),
InMsgs: atomic.LoadInt64(&ln.inMsgs),
OutMsgs: ln.outMsgs,
InBytes: atomic.LoadInt64(&ln.inBytes),
OutBytes: ln.outBytes,
NumSubs: uint32(len(ln.subs)),
Compression: ln.leaf.compression,
}
if opts != nil && opts.Subscriptions {
lni.Subs = make([]string, 0, len(ln.subs))
for _, sub := range ln.subs {
lni.Subs = append(lni.Subs, string(sub.subject))
}
}
ln.mu.Unlock()
leafnodes = append(leafnodes, lni)
}
}
return &Leafz{
ID: s.ID(),
Now: time.Now().UTC(),
NumLeafs: len(leafnodes),
Leafs: leafnodes,
}, nil
}
// HandleLeafz process HTTP requests for leafnode information.
func (s *Server) HandleLeafz(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
s.httpReqStats[LeafzPath]++
s.mu.Unlock()
subs, err := decodeBool(w, r, "subs")
if err != nil {
return
}
l, err := s.Leafz(&LeafzOptions{subs, r.URL.Query().Get("acc")})
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
b, err := json.MarshalIndent(l, "", " ")
if err != nil {
s.Errorf("Error marshaling response to /leafz request: %v", err)
}
// Handle response
ResponseHandler(w, r, b)
}
// Leafz represents detailed information on Leafnodes.
type AccountStatz struct {
ID string `json:"server_id"`
Now time.Time `json:"now"`
Accounts []*AccountStat `json:"account_statz"`
}
// AccountStatzOptions are options passed to account stats requests.
type AccountStatzOptions struct {
Accounts []string `json:"accounts"`
IncludeUnused bool `json:"include_unused"`
}
// Leafz returns a AccountStatz structure containing summary information about accounts.
func (s *Server) AccountStatz(opts *AccountStatzOptions) (*AccountStatz, error) {
stz := &AccountStatz{
ID: s.ID(),
Now: time.Now().UTC(),
Accounts: []*AccountStat{},
}
if opts == nil || len(opts.Accounts) == 0 {
s.accounts.Range(func(key, a any) bool {
acc := a.(*Account)
acc.mu.RLock()
if opts.IncludeUnused || acc.numLocalConnections() != 0 {
stz.Accounts = append(stz.Accounts, acc.statz())
}
acc.mu.RUnlock()
return true
})
} else {
for _, a := range opts.Accounts {
if acc, ok := s.accounts.Load(a); ok {
acc := acc.(*Account)
acc.mu.RLock()
if opts.IncludeUnused || acc.numLocalConnections() != 0 {
stz.Accounts = append(stz.Accounts, acc.statz())
}
acc.mu.RUnlock()
}
}
}
return stz, nil
}
// HandleAccountStatz process HTTP requests for statz information of all accounts.
func (s *Server) HandleAccountStatz(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
s.httpReqStats[AccountStatzPath]++
s.mu.Unlock()
unused, err := decodeBool(w, r, "unused")
if err != nil {
return
}
l, err := s.AccountStatz(&AccountStatzOptions{IncludeUnused: unused})
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
b, err := json.MarshalIndent(l, "", " ")
if err != nil {
s.Errorf("Error marshaling response to %s request: %v", AccountStatzPath, err)
return
}
// Handle response
ResponseHandler(w, r, b)
}
// ResponseHandler handles responses for monitoring routes.
func ResponseHandler(w http.ResponseWriter, r *http.Request, data []byte) {
handleResponse(http.StatusOK, w, r, data)
}
// handleResponse handles responses for monitoring routes with a specific HTTP status code.
func handleResponse(code int, w http.ResponseWriter, r *http.Request, data []byte) {
// Get callback from request
callback := r.URL.Query().Get("callback")
if callback != _EMPTY_ {
// Response for JSONP
w.Header().Set("Content-Type", "application/javascript")
w.WriteHeader(code)
fmt.Fprintf(w, "%s(%s)", callback, data)
} else {
// Otherwise JSON
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.WriteHeader(code)
w.Write(data)
}
}
func (reason ClosedState) String() string {
switch reason {
case ClientClosed:
return "Client Closed"
case AuthenticationTimeout:
return "Authentication Timeout"
case AuthenticationViolation:
return "Authentication Failure"
case TLSHandshakeError:
return "TLS Handshake Failure"
case SlowConsumerPendingBytes:
return "Slow Consumer (Pending Bytes)"
case SlowConsumerWriteDeadline:
return "Slow Consumer (Write Deadline)"
case WriteError:
return "Write Error"
case ReadError:
return "Read Error"
case ParseError:
return "Parse Error"
case StaleConnection:
return "Stale Connection"
case ProtocolViolation:
return "Protocol Violation"
case BadClientProtocolVersion:
return "Bad Client Protocol Version"
case WrongPort:
return "Incorrect Port"
case MaxConnectionsExceeded:
return "Maximum Connections Exceeded"
case MaxAccountConnectionsExceeded:
return "Maximum Account Connections Exceeded"
case MaxPayloadExceeded:
return "Maximum Message Payload Exceeded"
case MaxControlLineExceeded:
return "Maximum Control Line Exceeded"
case MaxSubscriptionsExceeded:
return "Maximum Subscriptions Exceeded"
case DuplicateRoute:
return "Duplicate Route"
case RouteRemoved:
return "Route Removed"
case ServerShutdown:
return "Server Shutdown"
case AuthenticationExpired:
return "Authentication Expired"
case WrongGateway:
return "Wrong Gateway"
case MissingAccount:
return "Missing Account"
case Revocation:
return "Credentials Revoked"
case InternalClient:
return "Internal Client"
case MsgHeaderViolation:
return "Message Header Violation"
case NoRespondersRequiresHeaders:
return "No Responders Requires Headers"
case ClusterNameConflict:
return "Cluster Name Conflict"
case DuplicateRemoteLeafnodeConnection:
return "Duplicate Remote LeafNode Connection"
case DuplicateClientID:
return "Duplicate Client ID"
case DuplicateServerName:
return "Duplicate Server Name"
case MinimumVersionRequired:
return "Minimum Version Required"
case ClusterNamesIdentical:
return "Cluster Names Identical"
case Kicked:
return "Kicked"
}
return "Unknown State"
}
// AccountzOptions are options passed to Accountz
type AccountzOptions struct {
// Account indicates that Accountz will return details for the account
Account string `json:"account"`
}
func newExtServiceLatency(l *serviceLatency) *jwt.ServiceLatency {
if l == nil {
return nil
}
return &jwt.ServiceLatency{
Sampling: jwt.SamplingRate(l.sampling),
Results: jwt.Subject(l.subject),
}
}
type ExtImport struct {
jwt.Import
Invalid bool `json:"invalid"`
Share bool `json:"share"`
Tracking bool `json:"tracking"`
TrackingHdr http.Header `json:"tracking_header,omitempty"`
Latency *jwt.ServiceLatency `json:"latency,omitempty"`
M1 *ServiceLatency `json:"m1,omitempty"`
}
type ExtExport struct {
jwt.Export
ApprovedAccounts []string `json:"approved_accounts,omitempty"`
RevokedAct map[string]time.Time `json:"revoked_activations,omitempty"`
}
type ExtVrIssues struct {
Description string `json:"description"`
Blocking bool `json:"blocking"`
Time bool `json:"time_check"`
}
type ExtMap map[string][]*MapDest
type AccountInfo struct {
AccountName string `json:"account_name"`
LastUpdate time.Time `json:"update_time,omitempty"`
IsSystem bool `json:"is_system,omitempty"`
Expired bool `json:"expired"`
Complete bool `json:"complete"`
JetStream bool `json:"jetstream_enabled"`
LeafCnt int `json:"leafnode_connections"`
ClientCnt int `json:"client_connections"`
SubCnt uint32 `json:"subscriptions"`
Mappings ExtMap `json:"mappings,omitempty"`
Exports []ExtExport `json:"exports,omitempty"`
Imports []ExtImport `json:"imports,omitempty"`
Jwt string `json:"jwt,omitempty"`
IssuerKey string `json:"issuer_key,omitempty"`
NameTag string `json:"name_tag,omitempty"`
Tags jwt.TagList `json:"tags,omitempty"`
Claim *jwt.AccountClaims `json:"decoded_jwt,omitempty"`
Vr []ExtVrIssues `json:"validation_result_jwt,omitempty"`
RevokedUser map[string]time.Time `json:"revoked_user,omitempty"`
Sublist *SublistStats `json:"sublist_stats,omitempty"`
Responses map[string]ExtImport `json:"responses,omitempty"`
}
type Accountz struct {
ID string `json:"server_id"`
Now time.Time `json:"now"`
SystemAccount string `json:"system_account,omitempty"`
Accounts []string `json:"accounts,omitempty"`
Account *AccountInfo `json:"account_detail,omitempty"`
}
// HandleAccountz process HTTP requests for account information.
func (s *Server) HandleAccountz(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
s.httpReqStats[AccountzPath]++
s.mu.Unlock()
if l, err := s.Accountz(&AccountzOptions{r.URL.Query().Get("acc")}); err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
} else if b, err := json.MarshalIndent(l, "", " "); err != nil {
s.Errorf("Error marshaling response to %s request: %v", AccountzPath, err)
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
} else {
ResponseHandler(w, r, b) // Handle response
}
}
func (s *Server) Accountz(optz *AccountzOptions) (*Accountz, error) {
a := &Accountz{
ID: s.ID(),
Now: time.Now().UTC(),
}
if sacc := s.SystemAccount(); sacc != nil {
a.SystemAccount = sacc.GetName()
}
if optz == nil || optz.Account == _EMPTY_ {
a.Accounts = []string{}
s.accounts.Range(func(key, value any) bool {
a.Accounts = append(a.Accounts, key.(string))
return true
})
return a, nil
}
aInfo, err := s.accountInfo(optz.Account)
if err != nil {
return nil, err
}
a.Account = aInfo
return a, nil
}
func newExtImport(v *serviceImport) ExtImport {
imp := ExtImport{
Invalid: true,
Import: jwt.Import{Type: jwt.Service},
}
if v != nil {
imp.Share = v.share
imp.Tracking = v.tracking
imp.Invalid = v.invalid
imp.Import = jwt.Import{
Subject: jwt.Subject(v.to),
Account: v.acc.Name,
Type: jwt.Service,
// Deprecated so we duplicate. Use LocalSubject.
To: jwt.Subject(v.from),
LocalSubject: jwt.RenamingSubject(v.from),
}
imp.TrackingHdr = v.trackingHdr
imp.Latency = newExtServiceLatency(v.latency)
if v.m1 != nil {
m1 := *v.m1
imp.M1 = &m1
}
}
return imp
}
func (s *Server) accountInfo(accName string) (*AccountInfo, error) {
var a *Account
if v, ok := s.accounts.Load(accName); !ok {
return nil, fmt.Errorf("Account %s does not exist", accName)
} else {
a = v.(*Account)
}
isSys := a == s.SystemAccount()
a.mu.RLock()
defer a.mu.RUnlock()
var vrIssues []ExtVrIssues
claim, _ := jwt.DecodeAccountClaims(a.claimJWT) // ignore error
if claim != nil {
vr := jwt.ValidationResults{}
claim.Validate(&vr)
vrIssues = make([]ExtVrIssues, len(vr.Issues))
for i, v := range vr.Issues {
vrIssues[i] = ExtVrIssues{v.Description, v.Blocking, v.TimeCheck}
}
}
collectRevocations := func(revocations map[string]int64) map[string]time.Time {
l := len(revocations)
if l == 0 {
return nil
}
rev := make(map[string]time.Time, l)
for k, v := range revocations {
rev[k] = time.Unix(v, 0)
}
return rev
}
exports := []ExtExport{}
for k, v := range a.exports.services {
e := ExtExport{
Export: jwt.Export{
Subject: jwt.Subject(k),
Type: jwt.Service,
},
ApprovedAccounts: []string{},
}
if v != nil {
e.Latency = newExtServiceLatency(v.latency)
e.TokenReq = v.tokenReq
e.ResponseType = jwt.ResponseType(v.respType.String())
for name := range v.approved {
e.ApprovedAccounts = append(e.ApprovedAccounts, name)
}
e.RevokedAct = collectRevocations(v.actsRevoked)
}
exports = append(exports, e)
}
for k, v := range a.exports.streams {
e := ExtExport{
Export: jwt.Export{
Subject: jwt.Subject(k),
Type: jwt.Stream,
},
ApprovedAccounts: []string{},
}
if v != nil {
e.TokenReq = v.tokenReq
for name := range v.approved {
e.ApprovedAccounts = append(e.ApprovedAccounts, name)
}
e.RevokedAct = collectRevocations(v.actsRevoked)
}
exports = append(exports, e)
}
imports := []ExtImport{}
for _, v := range a.imports.streams {
imp := ExtImport{
Invalid: true,
Import: jwt.Import{Type: jwt.Stream},
}
if v != nil {
imp.Invalid = v.invalid
imp.Import = jwt.Import{
Subject: jwt.Subject(v.from),
Account: v.acc.Name,
Type: jwt.Stream,
LocalSubject: jwt.RenamingSubject(v.to),
}
}
imports = append(imports, imp)
}
for _, v := range a.imports.services {
imports = append(imports, newExtImport(v))
}
responses := map[string]ExtImport{}
for k, v := range a.exports.responses {
responses[k] = newExtImport(v)
}
mappings := ExtMap{}
for _, m := range a.mappings {
var dests []*MapDest
var src string
if m == nil {
src = "nil"
if _, ok := mappings[src]; ok { // only set if not present (keep orig in case nil is used)
continue
}
dests = append(dests, &MapDest{})
} else {
src = m.src
for _, d := range m.dests {
dests = append(dests, &MapDest{d.tr.dest, d.weight, _EMPTY_})
}
for c, cd := range m.cdests {
for _, d := range cd {
dests = append(dests, &MapDest{d.tr.dest, d.weight, c})
}
}
}
mappings[src] = dests
}
return &AccountInfo{
accName,
a.updated.UTC(),
isSys,
a.expired.Load(),
!a.incomplete,
a.js != nil,
a.numLocalLeafNodes(),
a.numLocalConnections(),
a.sl.Count(),
mappings,
exports,
imports,
a.claimJWT,
a.Issuer,
a.nameTag,
a.tags,
claim,
vrIssues,
collectRevocations(a.usersRevoked),
a.sl.Stats(),
responses,
}, nil
}
// JSzOptions are options passed to Jsz
type JSzOptions struct {
Account string `json:"account,omitempty"`
Accounts bool `json:"accounts,omitempty"`
Streams bool `json:"streams,omitempty"`
Consumer bool `json:"consumer,omitempty"`
Config bool `json:"config,omitempty"`
LeaderOnly bool `json:"leader_only,omitempty"`
Offset int `json:"offset,omitempty"`
Limit int `json:"limit,omitempty"`
RaftGroups bool `json:"raft,omitempty"`
StreamLeaderOnly bool `json:"stream_leader_only,omitempty"`
}
// HealthzOptions are options passed to Healthz
type HealthzOptions struct {
// Deprecated: Use JSEnabledOnly instead
JSEnabled bool `json:"js-enabled,omitempty"`
JSEnabledOnly bool `json:"js-enabled-only,omitempty"`
JSServerOnly bool `json:"js-server-only,omitempty"`
Account string `json:"account,omitempty"`
Stream string `json:"stream,omitempty"`
Consumer string `json:"consumer,omitempty"`
Details bool `json:"details,omitempty"`
}
// ProfilezOptions are options passed to Profilez
type ProfilezOptions struct {
Name string `json:"name"`
Debug int `json:"debug"`
Duration time.Duration `json:"duration,omitempty"`
}
// IpqueueszOptions are options passed to Ipqueuesz
type IpqueueszOptions struct {
All bool `json:"all"`
Filter string `json:"filter"`
}
// RaftzOptions are options passed to Raftz
type RaftzOptions struct {
AccountFilter string `json:"account"`
GroupFilter string `json:"group"`
}
// StreamDetail shows information about the stream state and its consumers.
type StreamDetail struct {
Name string `json:"name"`
Created time.Time `json:"created"`
Cluster *ClusterInfo `json:"cluster,omitempty"`
Config *StreamConfig `json:"config,omitempty"`
State StreamState `json:"state,omitempty"`
Consumer []*ConsumerInfo `json:"consumer_detail,omitempty"`
Mirror *StreamSourceInfo `json:"mirror,omitempty"`
Sources []*StreamSourceInfo `json:"sources,omitempty"`
RaftGroup string `json:"stream_raft_group,omitempty"`
ConsumerRaftGroups []*RaftGroupDetail `json:"consumer_raft_groups,omitempty"`
}
// RaftGroupDetail shows information details about the Raft group.
type RaftGroupDetail struct {
Name string `json:"name"`
RaftGroup string `json:"raft_group,omitempty"`
}
type AccountDetail struct {
Name string `json:"name"`
Id string `json:"id"`
JetStreamStats
Streams []StreamDetail `json:"stream_detail,omitempty"`
}
// MetaClusterInfo shows information about the meta group.
type MetaClusterInfo struct {
Name string `json:"name,omitempty"`
Leader string `json:"leader,omitempty"`
Peer string `json:"peer,omitempty"`
Replicas []*PeerInfo `json:"replicas,omitempty"`
Size int `json:"cluster_size"`
Pending int `json:"pending"`
}
// JSInfo has detailed information on JetStream.
type JSInfo struct {
ID string `json:"server_id"`
Now time.Time `json:"now"`
Disabled bool `json:"disabled,omitempty"`
Config JetStreamConfig `json:"config,omitempty"`
JetStreamStats
Streams int `json:"streams"`
Consumers int `json:"consumers"`
Messages uint64 `json:"messages"`
Bytes uint64 `json:"bytes"`
Meta *MetaClusterInfo `json:"meta_cluster,omitempty"`
// aggregate raft info
AccountDetails []*AccountDetail `json:"account_details,omitempty"`
}
func (s *Server) accountDetail(jsa *jsAccount, optStreams, optConsumers, optCfg, optRaft, optStreamLeader bool) *AccountDetail {
jsa.mu.RLock()
acc := jsa.account
name := acc.GetName()
id := name
if acc.nameTag != _EMPTY_ {
name = acc.nameTag
}
jsa.usageMu.RLock()
totalMem, totalStore := jsa.storageTotals()
detail := AccountDetail{
Name: name,
Id: id,
JetStreamStats: JetStreamStats{
Memory: totalMem,
Store: totalStore,
API: JetStreamAPIStats{
Total: jsa.apiTotal,
Errors: jsa.apiErrors,
},
},
Streams: make([]StreamDetail, 0, len(jsa.streams)),
}
if reserved, ok := jsa.limits[_EMPTY_]; ok {
detail.JetStreamStats.ReservedMemory = uint64(reserved.MaxMemory)
detail.JetStreamStats.ReservedStore = uint64(reserved.MaxStore)
}
jsa.usageMu.RUnlock()
var streams []*stream
if optStreams {
for _, stream := range jsa.streams {
streams = append(streams, stream)
}
}
jsa.mu.RUnlock()
if js := s.getJetStream(); js != nil && optStreams {
for _, stream := range streams {
rgroup := stream.raftGroup()
ci := js.clusterInfo(rgroup)
var cfg *StreamConfig
if optCfg {
c := stream.config()
cfg = &c
}
// Skip if we are only looking for stream leaders.
if optStreamLeader && ci != nil && ci.Leader != s.Name() {
continue
}
sdet := StreamDetail{
Name: stream.name(),
Created: stream.createdTime(),
State: stream.state(),
Cluster: ci,
Config: cfg,
Mirror: stream.mirrorInfo(),
Sources: stream.sourcesInfo(),
}
if optRaft && rgroup != nil {
sdet.RaftGroup = rgroup.Name
sdet.ConsumerRaftGroups = make([]*RaftGroupDetail, 0)
}
if optConsumers {
for _, consumer := range stream.getPublicConsumers() {
cInfo := consumer.info()
if cInfo == nil {
continue
}
if !optCfg {
cInfo.Config = nil
}
sdet.Consumer = append(sdet.Consumer, cInfo)
if optRaft {
crgroup := consumer.raftGroup()
if crgroup != nil {
sdet.ConsumerRaftGroups = append(sdet.ConsumerRaftGroups,
&RaftGroupDetail{cInfo.Name, crgroup.Name},
)
}
}
}
}
detail.Streams = append(detail.Streams, sdet)
}
}
return &detail
}
func (s *Server) JszAccount(opts *JSzOptions) (*AccountDetail, error) {
js := s.getJetStream()
if js == nil {
return nil, fmt.Errorf("jetstream not enabled")
}
acc := opts.Account
account, ok := s.accounts.Load(acc)
if !ok {
return nil, fmt.Errorf("account %q not found", acc)
}
js.mu.RLock()
jsa, ok := js.accounts[account.(*Account).Name]
js.mu.RUnlock()
if !ok {
return nil, fmt.Errorf("account %q not jetstream enabled", acc)
}
return s.accountDetail(jsa, opts.Streams, opts.Consumer, opts.Config, opts.RaftGroups, opts.StreamLeaderOnly), nil
}
// helper to get cluster info from node via dummy group
func (s *Server) raftNodeToClusterInfo(node RaftNode) *ClusterInfo {
if node == nil {
return nil
}
peers := node.Peers()
peerList := make([]string, len(peers))
for i, p := range peers {
peerList[i] = p.ID
}
group := &raftGroup{
Name: _EMPTY_,
Peers: peerList,
node: node,
}
return s.getJetStream().clusterInfo(group)
}
// Jsz returns a Jsz structure containing information about JetStream.
func (s *Server) Jsz(opts *JSzOptions) (*JSInfo, error) {
// set option defaults
if opts == nil {
opts = &JSzOptions{}
}
if opts.Limit == 0 {
opts.Limit = 1024
}
if opts.Consumer {
opts.Streams = true
}
if opts.Streams && opts.Account == _EMPTY_ {
opts.Accounts = true
}
jsi := &JSInfo{
ID: s.ID(),
Now: time.Now().UTC(),
}
js := s.getJetStream()
if js == nil || !js.isEnabled() {
if opts.LeaderOnly {
return nil, fmt.Errorf("%w: not leader", errSkipZreq)
}
jsi.Disabled = true
return jsi, nil
}
js.mu.RLock()
isLeader := js.cluster == nil || js.cluster.isLeader()
js.mu.RUnlock()
if opts.LeaderOnly && !isLeader {
return nil, fmt.Errorf("%w: not leader", errSkipZreq)
}
var accounts []*jsAccount
js.mu.RLock()
jsi.Config = js.config
for _, info := range js.accounts {
accounts = append(accounts, info)
}
js.mu.RUnlock()
if mg := js.getMetaGroup(); mg != nil {
if ci := s.raftNodeToClusterInfo(mg); ci != nil {
jsi.Meta = &MetaClusterInfo{Name: ci.Name, Leader: ci.Leader, Peer: getHash(ci.Leader), Size: mg.ClusterSize()}
if isLeader {
jsi.Meta.Replicas = ci.Replicas
}
if ipq := s.jsAPIRoutedReqs; ipq != nil {
jsi.Meta.Pending = ipq.len()
}
}
}
jsi.JetStreamStats = *js.usageStats()
filterIdx := -1
for i, jsa := range accounts {
if jsa.acc().GetName() == opts.Account {
filterIdx = i
}
jsa.mu.RLock()
streams := make([]*stream, 0, len(jsa.streams))
for _, stream := range jsa.streams {
streams = append(streams, stream)
}
jsa.mu.RUnlock()
jsi.Streams += len(streams)
for _, stream := range streams {
streamState := stream.state()
jsi.Messages += streamState.Msgs
jsi.Bytes += streamState.Bytes
jsi.Consumers += streamState.Consumers
}
}
// filter logic
if filterIdx != -1 {
accounts = []*jsAccount{accounts[filterIdx]}
} else if opts.Accounts {
if opts.Offset != 0 {
slices.SortFunc(accounts, func(i, j *jsAccount) int { return cmp.Compare(i.acc().Name, j.acc().Name) })
if opts.Offset > len(accounts) {
accounts = []*jsAccount{}
} else {
accounts = accounts[opts.Offset:]
}
}
if opts.Limit != 0 {
if opts.Limit < len(accounts) {
accounts = accounts[:opts.Limit]
}
}
} else {
accounts = []*jsAccount{}
}
if len(accounts) > 0 {
jsi.AccountDetails = make([]*AccountDetail, 0, len(accounts))
}
// if wanted, obtain accounts/streams/consumer
for _, jsa := range accounts {
detail := s.accountDetail(jsa, opts.Streams, opts.Consumer, opts.Config, opts.RaftGroups, opts.StreamLeaderOnly)
jsi.AccountDetails = append(jsi.AccountDetails, detail)
}
return jsi, nil
}
// HandleJsz process HTTP requests for jetstream information.
func (s *Server) HandleJsz(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
s.httpReqStats[JszPath]++
s.mu.Unlock()
accounts, err := decodeBool(w, r, "accounts")
if err != nil {
return
}
streams, err := decodeBool(w, r, "streams")
if err != nil {
return
}
consumers, err := decodeBool(w, r, "consumers")
if err != nil {
return
}
config, err := decodeBool(w, r, "config")
if err != nil {
return
}
offset, err := decodeInt(w, r, "offset")
if err != nil {
return
}
limit, err := decodeInt(w, r, "limit")
if err != nil {
return
}
leader, err := decodeBool(w, r, "leader-only")
if err != nil {
return
}
rgroups, err := decodeBool(w, r, "raft")
if err != nil {
return
}
sleader, err := decodeBool(w, r, "stream-leader-only")
if err != nil {
return
}
l, err := s.Jsz(&JSzOptions{
Account: r.URL.Query().Get("acc"),
Accounts: accounts,
Streams: streams,
Consumer: consumers,
Config: config,
LeaderOnly: leader,
Offset: offset,
Limit: limit,
RaftGroups: rgroups,
StreamLeaderOnly: sleader,
})
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
b, err := json.MarshalIndent(l, "", " ")
if err != nil {
s.Errorf("Error marshaling response to /jsz request: %v", err)
}
// Handle response
ResponseHandler(w, r, b)
}
type HealthStatus struct {
Status string `json:"status"`
StatusCode int `json:"status_code,omitempty"`
Error string `json:"error,omitempty"`
Errors []HealthzError `json:"errors,omitempty"`
}
type HealthzError struct {
Type HealthZErrorType `json:"type"`
Account string `json:"account,omitempty"`
Stream string `json:"stream,omitempty"`
Consumer string `json:"consumer,omitempty"`
Error string `json:"error,omitempty"`
}
type HealthZErrorType int
const (
HealthzErrorConn HealthZErrorType = iota
HealthzErrorBadRequest
HealthzErrorJetStream
HealthzErrorAccount
HealthzErrorStream
HealthzErrorConsumer
)
func (t HealthZErrorType) String() string {
switch t {
case HealthzErrorConn:
return "CONNECTION"
case HealthzErrorBadRequest:
return "BAD_REQUEST"
case HealthzErrorJetStream:
return "JETSTREAM"
case HealthzErrorAccount:
return "ACCOUNT"
case HealthzErrorStream:
return "STREAM"
case HealthzErrorConsumer:
return "CONSUMER"
default:
return "unknown"
}
}
func (t HealthZErrorType) MarshalJSON() ([]byte, error) {
return json.Marshal(t.String())
}
func (t *HealthZErrorType) UnmarshalJSON(data []byte) error {
switch string(data) {
case `"CONNECTION"`:
*t = HealthzErrorConn
case `"BAD_REQUEST"`:
*t = HealthzErrorBadRequest
case `"JETSTREAM"`:
*t = HealthzErrorJetStream
case `"ACCOUNT"`:
*t = HealthzErrorAccount
case `"STREAM"`:
*t = HealthzErrorStream
case `"CONSUMER"`:
*t = HealthzErrorConsumer
default:
return fmt.Errorf("unknown healthz error type %q", data)
}
return nil
}
// https://datatracker.ietf.org/doc/html/draft-inadarei-api-health-check
func (s *Server) HandleHealthz(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
s.httpReqStats[HealthzPath]++
s.mu.Unlock()
jsEnabled, err := decodeBool(w, r, "js-enabled")
if err != nil {
return
}
if jsEnabled {
s.Warnf("Healthcheck: js-enabled deprecated, use js-enabled-only instead")
}
jsEnabledOnly, err := decodeBool(w, r, "js-enabled-only")
if err != nil {
return
}
jsServerOnly, err := decodeBool(w, r, "js-server-only")
if err != nil {
return
}
includeDetails, err := decodeBool(w, r, "details")
if err != nil {
return
}
hs := s.healthz(&HealthzOptions{
JSEnabled: jsEnabled,
JSEnabledOnly: jsEnabledOnly,
JSServerOnly: jsServerOnly,
Account: r.URL.Query().Get("account"),
Stream: r.URL.Query().Get("stream"),
Consumer: r.URL.Query().Get("consumer"),
Details: includeDetails,
})
code := hs.StatusCode
if hs.Error != _EMPTY_ {
s.Warnf("Healthcheck failed: %q", hs.Error)
} else if len(hs.Errors) != 0 {
s.Warnf("Healthcheck failed: %d errors", len(hs.Errors))
}
// Remove StatusCode from JSON representation when responding via HTTP
// since this is already in the response.
hs.StatusCode = 0
b, err := json.Marshal(hs)
if err != nil {
s.Errorf("Error marshaling response to /healthz request: %v", err)
}
handleResponse(code, w, r, b)
}
// Generate health status.
func (s *Server) healthz(opts *HealthzOptions) *HealthStatus {
var health = &HealthStatus{Status: "ok"}
// set option defaults
if opts == nil {
opts = &HealthzOptions{}
}
details := opts.Details
defer func() {
// for response with details enabled, set status to either "error" or "ok"
if details {
if len(health.Errors) != 0 {
health.Status = "error"
} else {
health.Status = "ok"
}
}
// if no specific status code was set, set it based on the presence of errors
if health.StatusCode == 0 {
if health.Error != _EMPTY_ || len(health.Errors) != 0 {
health.StatusCode = http.StatusServiceUnavailable
} else {
health.StatusCode = http.StatusOK
}
}
}()
if opts.Account == _EMPTY_ && opts.Stream != _EMPTY_ {
health.StatusCode = http.StatusBadRequest
if !details {
health.Status = "error"
health.Error = fmt.Sprintf("%q must not be empty when checking stream health", "account")
} else {
health.Errors = append(health.Errors, HealthzError{
Type: HealthzErrorBadRequest,
Error: fmt.Sprintf("%q must not be empty when checking stream health", "account"),
})
}
return health
}
if opts.Stream == _EMPTY_ && opts.Consumer != _EMPTY_ {
health.StatusCode = http.StatusBadRequest
if !details {
health.Status = "error"
health.Error = fmt.Sprintf("%q must not be empty when checking consumer health", "stream")
} else {
health.Errors = append(health.Errors, HealthzError{
Type: HealthzErrorBadRequest,
Error: fmt.Sprintf("%q must not be empty when checking consumer health", "stream"),
})
}
return health
}
if err := s.readyForConnections(time.Millisecond); err != nil {
health.StatusCode = http.StatusInternalServerError
health.Status = "error"
if !details {
health.Error = err.Error()
} else {
health.Errors = append(health.Errors, HealthzError{
Type: HealthzErrorConn,
Error: err.Error(),
})
}
return health
}
sopts := s.getOpts()
// If JS is not enabled in the config, we stop.
if !sopts.JetStream {
return health
}
// Access the Jetstream state to perform additional checks.
js := s.getJetStream()
const na = "unavailable"
if !js.isEnabled() {
health.StatusCode = http.StatusServiceUnavailable
health.Status = na
if !details {
health.Error = NewJSNotEnabledError().Error()
} else {
health.Errors = append(health.Errors, HealthzError{
Type: HealthzErrorJetStream,
Error: NewJSNotEnabledError().Error(),
})
}
return health
}
// Only check if JS is enabled, skip meta and asset check.
if opts.JSEnabledOnly || opts.JSEnabled {
return health
}
// Clustered JetStream
js.mu.RLock()
cc := js.cluster
js.mu.RUnlock()
// Currently single server we make sure the streams were recovered.
if cc == nil {
sdir := js.config.StoreDir
// Whip through account folders and pull each stream name.
fis, _ := os.ReadDir(sdir)
var accFound, streamFound, consumerFound bool
for _, fi := range fis {
if fi.Name() == snapStagingDir {
continue
}
if opts.Account != _EMPTY_ {
if fi.Name() != opts.Account {
continue
}
accFound = true
}
acc, err := s.LookupAccount(fi.Name())
if err != nil {
if !details {
health.Status = na
health.Error = fmt.Sprintf("JetStream account '%s' could not be resolved", fi.Name())
return health
}
health.Errors = append(health.Errors, HealthzError{
Type: HealthzErrorAccount,
Account: fi.Name(),
Error: fmt.Sprintf("JetStream account '%s' could not be resolved", fi.Name()),
})
continue
}
sfis, _ := os.ReadDir(filepath.Join(sdir, fi.Name(), "streams"))
for _, sfi := range sfis {
if opts.Stream != _EMPTY_ {
if sfi.Name() != opts.Stream {
continue
}
streamFound = true
}
stream := sfi.Name()
s, err := acc.lookupStream(stream)
if err != nil {
if !details {
health.Status = na
health.Error = fmt.Sprintf("JetStream stream '%s > %s' could not be recovered", acc, stream)
return health
}
health.Errors = append(health.Errors, HealthzError{
Type: HealthzErrorStream,
Account: acc.Name,
Stream: stream,
Error: fmt.Sprintf("JetStream stream '%s > %s' could not be recovered", acc, stream),
})
continue
}
if streamFound {
// if consumer option is passed, verify that the consumer exists on stream
if opts.Consumer != _EMPTY_ {
for _, cons := range s.consumers {
if cons.name == opts.Consumer {
consumerFound = true
break
}
}
}
break
}
}
if accFound {
break
}
}
if opts.Account != _EMPTY_ && !accFound {
health.StatusCode = http.StatusNotFound
if !details {
health.Status = na
health.Error = fmt.Sprintf("JetStream account %q not found", opts.Account)
} else {
health.Errors = []HealthzError{
{
Type: HealthzErrorAccount,
Account: opts.Account,
Error: fmt.Sprintf("JetStream account %q not found", opts.Account),
},
}
}
return health
}
if opts.Stream != _EMPTY_ && !streamFound {
health.StatusCode = http.StatusNotFound
if !details {
health.Status = na
health.Error = fmt.Sprintf("JetStream stream %q not found on account %q", opts.Stream, opts.Account)
} else {
health.Errors = []HealthzError{
{
Type: HealthzErrorStream,
Account: opts.Account,
Stream: opts.Stream,
Error: fmt.Sprintf("JetStream stream %q not found on account %q", opts.Stream, opts.Account),
},
}
}
return health
}
if opts.Consumer != _EMPTY_ && !consumerFound {
health.StatusCode = http.StatusNotFound
if !details {
health.Status = na
health.Error = fmt.Sprintf("JetStream consumer %q not found for stream %q on account %q", opts.Consumer, opts.Stream, opts.Account)
} else {
health.Errors = []HealthzError{
{
Type: HealthzErrorConsumer,
Account: opts.Account,
Stream: opts.Stream,
Consumer: opts.Consumer,
Error: fmt.Sprintf("JetStream consumer %q not found for stream %q on account %q", opts.Consumer, opts.Stream, opts.Account),
},
}
}
}
return health
}
// If we are here we want to check for any assets assigned to us.
var meta RaftNode
js.mu.RLock()
meta = cc.meta
js.mu.RUnlock()
// If no meta leader.
if meta == nil || meta.GroupLeader() == _EMPTY_ {
if !details {
health.Status = na
health.Error = "JetStream has not established contact with a meta leader"
} else {
health.Errors = []HealthzError{
{
Type: HealthzErrorJetStream,
Error: "JetStream has not established contact with a meta leader",
},
}
}
return health
}
// If we are not current with the meta leader.
if !meta.Healthy() {
if !details {
health.Status = na
health.Error = "JetStream is not current with the meta leader"
} else {
health.Errors = []HealthzError{
{
Type: HealthzErrorJetStream,
Error: "JetStream is not current with the meta leader",
},
}
}
return health
}
// If JSServerOnly is true, then do not check further accounts, streams and consumers.
if opts.JSServerOnly {
return health
}
// Are we still recovering meta layer?
if js.isMetaRecovering() {
if !details {
health.Status = na
health.Error = "JetStream is still recovering meta layer"
} else {
health.Errors = []HealthzError{
{
Type: HealthzErrorJetStream,
Error: "JetStream is still recovering meta layer",
},
}
}
return health
}
// Range across all accounts, the streams assigned to them, and the consumers.
// If they are assigned to this server check their status.
ourID := meta.ID()
// Copy the meta layer so we do not need to hold the js read lock for an extended period of time.
var streams map[string]map[string]*streamAssignment
js.mu.RLock()
if opts.Account == _EMPTY_ {
// Collect all relevant streams and consumers.
streams = make(map[string]map[string]*streamAssignment, len(cc.streams))
for acc, asa := range cc.streams {
nasa := make(map[string]*streamAssignment)
for stream, sa := range asa {
// If we are a member and we are not being restored, select for check.
if sa.Group.isMember(ourID) && sa.Restore == nil {
csa := sa.copyGroup()
csa.consumers = make(map[string]*consumerAssignment)
for consumer, ca := range sa.consumers {
if ca.Group.isMember(ourID) {
// Use original here. Not a copy.
csa.consumers[consumer] = ca
}
}
nasa[stream] = csa
}
}
streams[acc] = nasa
}
} else {
streams = make(map[string]map[string]*streamAssignment, 1)
asa, ok := cc.streams[opts.Account]
if !ok {
health.StatusCode = http.StatusNotFound
if !details {
health.Status = na
health.Error = fmt.Sprintf("JetStream account %q not found", opts.Account)
} else {
health.Errors = []HealthzError{
{
Type: HealthzErrorAccount,
Account: opts.Account,
Error: fmt.Sprintf("JetStream account %q not found", opts.Account),
},
}
}
js.mu.RUnlock()
return health
}
nasa := make(map[string]*streamAssignment)
if opts.Stream != _EMPTY_ {
sa, ok := asa[opts.Stream]
if !ok || !sa.Group.isMember(ourID) {
health.StatusCode = http.StatusNotFound
if !details {
health.Status = na
health.Error = fmt.Sprintf("JetStream stream %q not found on account %q", opts.Stream, opts.Account)
} else {
health.Errors = []HealthzError{
{
Type: HealthzErrorStream,
Account: opts.Account,
Stream: opts.Stream,
Error: fmt.Sprintf("JetStream stream %q not found on account %q", opts.Stream, opts.Account),
},
}
}
js.mu.RUnlock()
return health
}
csa := sa.copyGroup()
csa.consumers = make(map[string]*consumerAssignment)
var consumerFound bool
for consumer, ca := range sa.consumers {
if opts.Consumer != _EMPTY_ {
if consumer != opts.Consumer || !ca.Group.isMember(ourID) {
continue
}
consumerFound = true
}
// If we are a member and we are not being restored, select for check.
if sa.Group.isMember(ourID) && sa.Restore == nil {
csa.consumers[consumer] = ca
}
if consumerFound {
break
}
}
if opts.Consumer != _EMPTY_ && !consumerFound {
health.StatusCode = http.StatusNotFound
if !details {
health.Status = na
health.Error = fmt.Sprintf("JetStream consumer %q not found for stream %q on account %q", opts.Consumer, opts.Stream, opts.Account)
} else {
health.Errors = []HealthzError{
{
Type: HealthzErrorConsumer,
Account: opts.Account,
Stream: opts.Stream,
Consumer: opts.Consumer,
Error: fmt.Sprintf("JetStream consumer %q not found for stream %q on account %q", opts.Consumer, opts.Stream, opts.Account),
},
}
}
js.mu.RUnlock()
return health
}
nasa[opts.Stream] = csa
} else {
for stream, sa := range asa {
// If we are a member and we are not being restored, select for check.
if sa.Group.isMember(ourID) && sa.Restore == nil {
csa := sa.copyGroup()
csa.consumers = make(map[string]*consumerAssignment)
for consumer, ca := range sa.consumers {
if ca.Group.isMember(ourID) {
csa.consumers[consumer] = ca
}
}
nasa[stream] = csa
}
}
}
streams[opts.Account] = nasa
}
js.mu.RUnlock()
// Use our copy to traverse so we do not need to hold the js lock.
for accName, asa := range streams {
acc, err := s.LookupAccount(accName)
if err != nil && len(asa) > 0 {
if !details {
health.Status = na
health.Error = fmt.Sprintf("JetStream can not lookup account %q: %v", accName, err)
return health
}
health.Errors = append(health.Errors, HealthzError{
Type: HealthzErrorAccount,
Account: accName,
Error: fmt.Sprintf("JetStream can not lookup account %q: %v", accName, err),
})
continue
}
for stream, sa := range asa {
// Make sure we can look up
if err := js.isStreamHealthy(acc, sa); err != nil {
if !details {
health.Status = na
health.Error = fmt.Sprintf("JetStream stream '%s > %s' is not current: %s", accName, stream, err)
return health
}
health.Errors = append(health.Errors, HealthzError{
Type: HealthzErrorStream,
Account: accName,
Stream: stream,
Error: fmt.Sprintf("JetStream stream '%s > %s' is not current: %s", accName, stream, err),
})
continue
}
mset, _ := acc.lookupStream(stream)
// Now check consumers.
for consumer, ca := range sa.consumers {
if err := js.isConsumerHealthy(mset, consumer, ca); err != nil {
if !details {
health.Status = na
health.Error = fmt.Sprintf("JetStream consumer '%s > %s > %s' is not current: %s", acc, stream, consumer, err)
return health
}
health.Errors = append(health.Errors, HealthzError{
Type: HealthzErrorConsumer,
Account: accName,
Stream: stream,
Consumer: consumer,
Error: fmt.Sprintf("JetStream consumer '%s > %s > %s' is not current: %s", acc, stream, consumer, err),
})
}
}
}
}
// Success.
return health
}
type ExpvarzStatus struct {
Memstats json.RawMessage `json:"memstats"`
Cmdline json.RawMessage `json:"cmdline"`
}
func (s *Server) expvarz(_ *ExpvarzEventOptions) *ExpvarzStatus {
var stat ExpvarzStatus
const memStatsKey = "memstats"
const cmdLineKey = "cmdline"
expvar.Do(func(v expvar.KeyValue) {
switch v.Key {
case memStatsKey:
stat.Memstats = json.RawMessage(v.Value.String())
case cmdLineKey:
stat.Cmdline = json.RawMessage(v.Value.String())
}
})
return &stat
}
type ProfilezStatus struct {
Profile []byte `json:"profile"`
Error string `json:"error"`
}
func (s *Server) profilez(opts *ProfilezOptions) *ProfilezStatus {
var buffer bytes.Buffer
switch opts.Name {
case _EMPTY_:
return &ProfilezStatus{
Error: "Profile name not specified",
}
case "cpu":
if opts.Duration <= 0 || opts.Duration > 15*time.Second {
return &ProfilezStatus{
Error: fmt.Sprintf("Duration %s should be between 0s and 15s", opts.Duration),
}
}
if err := pprof.StartCPUProfile(&buffer); err != nil {
return &ProfilezStatus{
Error: fmt.Sprintf("Failed to start CPU profile: %s", err),
}
}
time.Sleep(opts.Duration)
pprof.StopCPUProfile()
default:
profile := pprof.Lookup(opts.Name)
if profile == nil {
return &ProfilezStatus{
Error: fmt.Sprintf("Profile %q not found", opts.Name),
}
}
if err := profile.WriteTo(&buffer, opts.Debug); err != nil {
return &ProfilezStatus{
Error: fmt.Sprintf("Profile %q error: %s", opts.Name, err),
}
}
}
return &ProfilezStatus{
Profile: buffer.Bytes(),
}
}
type RaftzGroup struct {
ID string `json:"id"`
State string `json:"state"`
Size int `json:"size"`
QuorumNeeded int `json:"quorum_needed"`
Observer bool `json:"observer,omitempty"`
Paused bool `json:"paused,omitempty"`
Committed uint64 `json:"committed"`
Applied uint64 `json:"applied"`
CatchingUp bool `json:"catching_up,omitempty"`
Leader string `json:"leader,omitempty"`
EverHadLeader bool `json:"ever_had_leader"`
Term uint64 `json:"term"`
Vote string `json:"voted_for,omitempty"`
PTerm uint64 `json:"pterm"`
PIndex uint64 `json:"pindex"`
IPQPropLen int `json:"ipq_proposal_len"`
IPQEntryLen int `json:"ipq_entry_len"`
IPQRespLen int `json:"ipq_resp_len"`
IPQApplyLen int `json:"ipq_apply_len"`
WAL StreamState `json:"wal"`
WALError error `json:"wal_error,omitempty"`
Peers map[string]RaftzGroupPeer `json:"peers"`
}
type RaftzGroupPeer struct {
Name string `json:"name"`
Known bool `json:"known"`
LastReplicatedIndex uint64 `json:"last_replicated_index,omitempty"`
LastSeen string `json:"last_seen,omitempty"`
}
type RaftzStatus map[string]map[string]RaftzGroup
func (s *Server) HandleRaftz(w http.ResponseWriter, r *http.Request) {
if s.raftNodes == nil {
w.WriteHeader(404)
w.Write([]byte("No Raft nodes registered"))
return
}
groups := s.Raftz(&RaftzOptions{
AccountFilter: r.URL.Query().Get("acc"),
GroupFilter: r.URL.Query().Get("group"),
})
if groups == nil {
w.WriteHeader(404)
w.Write([]byte("No Raft nodes returned, check supplied filters"))
return
}
b, _ := json.MarshalIndent(groups, "", " ")
ResponseHandler(w, r, b)
}
func (s *Server) Raftz(opts *RaftzOptions) *RaftzStatus {
afilter, gfilter := opts.AccountFilter, opts.GroupFilter
if afilter == _EMPTY_ {
if sys := s.SystemAccount(); sys != nil {
afilter = sys.Name
} else {
return nil
}
}
groups := map[string]RaftNode{}
infos := RaftzStatus{} // account -> group ID
s.rnMu.RLock()
if gfilter != _EMPTY_ {
if rg, ok := s.raftNodes[gfilter]; ok && rg != nil {
if n, ok := rg.(*raft); ok {
if n.accName == afilter {
groups[gfilter] = rg
}
}
}
} else {
for name, rg := range s.raftNodes {
if rg == nil {
continue
}
if n, ok := rg.(*raft); ok {
if n.accName != afilter {
continue
}
groups[name] = rg
}
}
}
s.rnMu.RUnlock()
for name, rg := range groups {
n, ok := rg.(*raft)
if n == nil || !ok {
continue
}
if _, ok := infos[n.accName]; !ok {
infos[n.accName] = map[string]RaftzGroup{}
}
// Only take the lock once, using the public RaftNode functions would
// cause us to take and release the locks over and over again.
n.RLock()
info := RaftzGroup{
ID: n.id,
State: RaftState(n.state.Load()).String(),
Size: n.csz,
QuorumNeeded: n.qn,
Observer: n.observer,
Paused: n.paused,
Committed: n.commit,
Applied: n.applied,
CatchingUp: n.catchup != nil,
Leader: n.leader,
EverHadLeader: n.pleader.Load(),
Term: n.term,
Vote: n.vote,
PTerm: n.pterm,
PIndex: n.pindex,
IPQPropLen: n.prop.len(),
IPQEntryLen: n.entry.len(),
IPQRespLen: n.resp.len(),
IPQApplyLen: n.apply.len(),
WALError: n.werr,
Peers: map[string]RaftzGroupPeer{},
}
n.wal.FastState(&info.WAL)
for id, p := range n.peers {
if id == n.id {
continue
}
peer := RaftzGroupPeer{
Name: s.serverNameForNode(id),
Known: p.kp,
LastReplicatedIndex: p.li,
}
if p.ts > 0 {
peer.LastSeen = time.Since(time.Unix(0, p.ts)).String()
}
info.Peers[id] = peer
}
n.RUnlock()
infos[n.accName][name] = info
}
return &infos
}
|