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 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151
|
#Copyright 2008 Orbitz WorldWide
#
#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.
# make / work consistently between python 2.x and 3.x
# https://www.python.org/dev/peps/pep-0238/
from __future__ import division
import math
import random
import re
import time
from datetime import datetime, timedelta
from functools import reduce
from six.moves import range, zip
import six
try:
from itertools import izip, izip_longest
except ImportError:
# Python 3
from itertools import zip_longest as izip_longest
izip = zip
from os import environ
from django.conf import settings
from graphite.errors import NormalizeEmptyResultError, InputParameterError
from graphite.events import models
from graphite.functions import SeriesFunction, ParamTypes, Param, ParamTypeAggFunc, getAggFunc, safe
from graphite.logger import log
from graphite.render.attime import getUnitString, parseTimeOffset, parseATTime, SECONDS_STRING, MINUTES_STRING, HOURS_STRING, DAYS_STRING, WEEKS_STRING, MONTHS_STRING, YEARS_STRING
from graphite.render.evaluator import evaluateTarget
from graphite.render.grammar import grammar
from graphite.storage import STORE
from graphite.util import epoch, epoch_to_dt, timestamp, deltaseconds
# XXX format_units() should go somewhere else
if environ.get('READTHEDOCS'):
format_units = lambda *args, **kwargs: (0,'')
else:
from graphite.render.glyph import format_units
from graphite.render.datalib import TimeSeries
NAN = float('NaN')
INF = float('inf')
DAY = 86400
HOUR = 3600
MINUTE = 60
#Utility functions
# In Py2, None < (any integer) . Use -inf for same sorting on Python 3
def keyFunc(func):
def safeFunc(values):
val = func(values)
return val if val is not None else -INF
return safeFunc
# Greatest common divisor
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
# Least common multiple
def lcm(a, b):
if a == b: return a
if a < b: (a, b) = (b, a) #ensure a > b
return a // gcd(a,b) * b
# check list of values against xFilesFactor
def xffValues(values, xFilesFactor):
if not values:
return False
return xff(len([v for v in values if v is not None]), len(values), xFilesFactor)
def xff(nonNull, total, xFilesFactor=None):
if not nonNull or not total:
return False
return nonNull / total >= (xFilesFactor if xFilesFactor is not None else settings.DEFAULT_XFILES_FACTOR)
def getNodeOrTag(series, n, pathExpression=None):
try:
# if n is an integer use it as a node, otherwise catch ValueError and treat it as a tag
if n == int(n):
# first split off any tags, then list of nodes is name split on .
return (pathExpression or series.name).split(';', 2)[0].split('.')[n]
except (ValueError, IndexError):
# if node isn't an integer or isn't found then try it as a tag name
pass
# return tag value, default to '' if not found
return series.tags.get(str(n), '')
def aggKey(series, nodes, pathExpression=None):
# if series.name looks like it includes a function, use the first path expression
if pathExpression is None and series.name[-1] == ')':
pathExpression = _getFirstPathExpression(series.name)
return '.'.join([getNodeOrTag(series, n, pathExpression) for n in nodes])
def normalize(seriesLists):
if seriesLists:
seriesList = reduce(lambda L1,L2: L1+L2,seriesLists)
if seriesList:
step = reduce(lcm,[s.step for s in seriesList])
for s in seriesList:
s.consolidate( step // s.step )
start = min([s.start for s in seriesList])
end = max([s.end for s in seriesList])
end -= (end - start) % step
return (seriesList,start,end,step)
raise NormalizeEmptyResultError()
def matchSeries(seriesList1, seriesList2):
assert len(seriesList2) == len(seriesList1), "The number of series in each argument must be the same"
return izip(sorted(seriesList1, key=lambda a: a.name), sorted(seriesList2, key=lambda a: a.name))
def trimRecent(seriesList):
# trim right side of the graph to avoid dip when only part of most recent metrics has entered the system
for s in seriesList:
if len(s) > 1:
if (s[-1] is None) and (s[-2] is not None):
for sl in seriesList:
sl[-1] = None
break
for s in seriesList:
if len(s) > 2:
if (s[-2] is None) and (s[-3] is not None):
for sl in seriesList:
sl[-2] = None
break
return (seriesList)
def _compressPeriodicGaps(series):
# removing periodic gaps, using summarize(seriesList, '<desired step>', 'last')
# but trying to auto detect step by first three existing values
consolidate = series.consolidationFunc
tags = series.tags
xFilesFactor = series.xFilesFactor
pathExpression = series.pathExpression
# try to detect interval
firstSeen = 0
secondSeen = 0
interval = None
for i, value in enumerate(series):
if value:
if firstSeen > 0:
secondSeen = i
break
else:
firstSeen = i
stepGuess = secondSeen - firstSeen
thirdSeen = secondSeen + stepGuess
if stepGuess > 1 and thirdSeen <= len(series) - 2: # protecting list boundaries
if series[thirdSeen]: # if we predict value
if series[thirdSeen - 1] is None and series[thirdSeen + 1] is None: # ..and it surrounded by Nones
interval = stepGuess * series.step # we probably guessed interval.
if interval:
newStart = series.start + firstSeen * series.step # skipping initial Nones
(newValues, _) = _summarizeValues(series, 'last', interval, newStart, series.end)
newEnd = newStart + interval * (len(newValues) - 1) # calculating new end from summarized values
return TimeSeries(series.name, newStart, newEnd, interval, newValues,
consolidate=consolidate, tags=tags, xFilesFactor=xFilesFactor, pathExpression=pathExpression)
else:
# we couldn't detect interval, just return untouched series
return series
def formatPathExpressions(seriesList):
# remove duplicates
pathExpressions = []
[pathExpressions.append(s.pathExpression) for s in seriesList if not pathExpressions.count(s.pathExpression)]
return ','.join(pathExpressions)
# Series Functions
def aggregate(requestContext, seriesList, func, xFilesFactor=None):
"""
Aggregate series using the specified function.
Example:
.. code-block:: none
&target=aggregate(host.cpu-[0-7].cpu-{user,system}.value, "sum")
This would be the equivalent of
.. code-block:: none
&target=sumSeries(host.cpu-[0-7].cpu-{user,system}.value)
This function can be used with aggregation functions ``average`` (or ``avg``), ``avg_zero``,
``median``, ``sum`` (or ``total``), ``min``, ``max``, ``diff``, ``stddev``, ``count``,
``range`` (or ``rangeOf``) , ``multiply`` & ``last`` (or ``current``).
"""
# strip Series from func if func was passed like sumSeries
rawFunc = func
if func[-6:] == 'Series':
func = func[:-6]
consolidationFunc = getAggFunc(func, rawFunc)
# if seriesList is empty then just short-circuit
if not seriesList:
return []
# if seriesList is a single series then wrap it for normalize
if isinstance(seriesList[0], TimeSeries):
seriesList = [seriesList]
try:
(seriesList, start, end, step) = normalize(seriesList)
except NormalizeEmptyResultError:
return []
if (settings.RENDER_TRIM_RECENT_IN_AGGREGATE):
seriesList = trimRecent(seriesList)
xFilesFactor = xFilesFactor if xFilesFactor is not None else requestContext.get('xFilesFactor')
name = "%sSeries(%s)" % (func, formatPathExpressions(seriesList))
values = ( consolidationFunc(row) if xffValues(row, xFilesFactor) else None for row in izip_longest(*seriesList) )
tags = seriesList[0].tags
for series in seriesList:
tags = {tag: tags[tag] for tag in tags if tag in series.tags and tags[tag] == series.tags[tag]}
if 'name' not in tags:
tags['name'] = name
tags['aggregatedBy'] = func
series = TimeSeries(name, start, end, step, values, xFilesFactor=xFilesFactor, tags=tags)
return [series]
aggregate.group = 'Combine'
aggregate.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('func', ParamTypes.aggFunc, required=True),
Param('xFilesFactor', ParamTypes.float),
]
def aggregateSeriesLists(requestContext, seriesListFirstPos, seriesListSecondPos, func, xFilesFactor=None):
"""
Iterates over a two lists and aggregates using specified function
list1[0] to list2[0], list1[1] to list2[1] and so on.
The lists will need to be the same length
Position of seriesList matters. For example using "sum" function
``aggregateSeriesLists(list1[0..n], list2[0..n], "sum")``
it would find sum for each member
of the list ``list1[0] + list2[0], list1[1] + list2[1], list1[n] + list2[n]``.
Example:
.. code-block:: none
&target=aggregateSeriesLists(mining.{carbon,graphite,diamond}.extracted,mining.{carbon,graphite,diamond}.shipped, 'sum')
An example above would be the same as running :py:func:`aggregate <aggregate>` for each member of the list:
.. code-block:: none
?target=aggregate(mining.carbon.extracted,mining.carbon.shipped, 'sum')
&target=aggregate(mining.graphite.extracted,mining.graphite.shipped, 'sum')
&target=aggregate(mining.diamond.extracted,mining.diamond.shipped, 'sum')
This function can be used with aggregation functions ``average`` (or ``avg``), ``avg_zero``,
``median``, ``sum`` (or ``total``), ``min``, ``max``, ``diff``, ``stddev``, ``count``,
``range`` (or ``rangeOf``) , ``multiply`` & ``last`` (or ``current``).
"""
if len(seriesListFirstPos) != len(seriesListSecondPos):
raise InputParameterError(
"seriesListFirstPos and seriesListSecondPos argument must have equal length")
results = []
for i in range(0, len(seriesListFirstPos)):
firstSeries = seriesListFirstPos[i]
secondSeries = seriesListSecondPos[i]
aggregated = aggregate(requestContext, (firstSeries, secondSeries), func, xFilesFactor=xFilesFactor)
if not aggregated: # empty list, no data found
continue
result = aggregated[0] # aggregate() can only return len 1 list
result.name = result.name[:result.name.find('Series(')] + 'Series(%s,%s)' % (firstSeries.name, secondSeries.name)
results.append(result)
return results
aggregateSeriesLists.group = 'Combine'
aggregateSeriesLists.params = [
Param('seriesListFirstPos', ParamTypes.seriesList, required=True),
Param('seriesListSecondPos', ParamTypes.seriesList, required=True),
Param('func', ParamTypes.aggFunc, required=True),
Param('xFilesFactor', ParamTypes.float),
]
def sumSeries(requestContext, *seriesLists):
"""
Short form: sum()
This will add metrics together and return the sum at each datapoint. (See
integral for a sum over time)
Example:
.. code-block:: none
&target=sum(company.server.application*.requestsHandled)
This would show the sum of all requests handled per minute (provided
requestsHandled are collected once a minute). If metrics with different
retention rates are combined, the coarsest metric is graphed, and the sum
of the other metrics is averaged for the metrics with finer retention rates.
This is an alias for :py:func:`aggregate <aggregate>` with aggregation ``sum``.
"""
return aggregate(requestContext, seriesLists, 'sum')
sumSeries.group = 'Combine'
sumSeries.params = [
Param('seriesLists', ParamTypes.seriesList, required=True, multiple=True),
]
sumSeries.aggregator = True
def sumSeriesLists(requestContext, seriesListFirstPos, seriesListSecondPos):
"""
Iterates over a two lists and subtracts series lists 2 through n from series 1
list1[0] to list2[0], list1[1] to list2[1] and so on.
The lists will need to be the same length
Example:
.. code-block:: none
&target=sumSeriesLists(mining.{carbon,graphite,diamond}.extracted,mining.{carbon,graphite,diamond}.shipped)
An example above would be the same as running :py:func:`sumSeries <sumSeries>` for each member of the list:
.. code-block:: none
?target=sumSeries(mining.carbon.extracted,mining.carbon.shipped)
&target=sumSeries(mining.graphite.extracted,mining.graphite.shipped)
&target=sumSeries(mining.diamond.extracted,mining.diamond.shipped)
This is an alias for :py:func:`aggregateSeriesLists <aggregateSeriesLists>` with aggregation ``sum``.
"""
return aggregateSeriesLists(requestContext, seriesListFirstPos, seriesListSecondPos, 'sum')
sumSeriesLists.group = 'Combine'
sumSeriesLists.params = [
Param('seriesListFirstPos', ParamTypes.seriesList, required=True),
Param('seriesListSecondPos', ParamTypes.seriesList, required=True),
]
sumSeriesLists.aggregator = True
def sumSeriesWithWildcards(requestContext, seriesList, *position): #XXX
"""
Categorizes the provided series in groups by name, by ignoring
("wildcarding") the given position(s) and calls sumSeries on each group.
Important: the introduction of wildcards only happens *after* retrieving
the input.
Example:
.. code-block:: none
&target=sumSeriesWithWildcards(host.cpu-[0-7].cpu-{user,system}.value, 1)
This would be the equivalent of
.. code-block:: none
&target=sumSeries(host.cpu-[0-7].cpu-user.value)&target=sumSeries(host.cpu-[0-7].cpu-system.value)
This is an alias for :py:func:`aggregateWithWildcards <aggregateWithWildcards>` with aggregation ``sum``.
"""
return aggregateWithWildcards(requestContext, seriesList, 'sum', *position)
sumSeriesWithWildcards.group = 'Combine'
sumSeriesWithWildcards.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('position', ParamTypes.node, multiple=True),
]
sumSeriesWithWildcards.aggregator = True
def averageSeriesWithWildcards(requestContext, seriesList, *position): #XXX
"""
Categorizes the provided series in groups by name, by ignoring
("wildcarding") the given position(s) and calls averageSeries on each group.
Important: the introduction of wildcards only happens *after* retrieving
the input.
Example:
.. code-block:: none
&target=averageSeriesWithWildcards(host.cpu-[0-7].cpu-{user,system}.value, 1)
This would be the equivalent of
.. code-block:: none
&target=averageSeries(host.cpu-[0-7].cpu-user.value)&target=averageSeries(host.cpu-[0-7].cpu-system.value)
This is an alias for :py:func:`aggregateWithWildcards <aggregateWithWildcards>` with aggregation ``average``.
"""
return aggregateWithWildcards(requestContext, seriesList, 'average', *position)
averageSeriesWithWildcards.group = 'Combine'
averageSeriesWithWildcards.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('position', ParamTypes.node, multiple=True),
]
averageSeriesWithWildcards.aggregator = True
def multiplySeriesWithWildcards(requestContext, seriesList, *position): #XXX
"""
Categorizes the provided series in groups by name, by ignoring
("wildcarding") the given position(s) and calls multiplySeries on each group.
Important: the introduction of wildcards only happens *after* retrieving
the input.
Example:
.. code-block:: none
&target=multiplySeriesWithWildcards(web.host-[0-7].{avg-response,total-request}.value, 2)
This would be the equivalent of
.. code-block:: none
&target=multiplySeries(web.host-0.{avg-response,total-request}.value)&target=multiplySeries(web.host-1.{avg-response,total-request}.value)...
This is an alias for :py:func:`aggregateWithWildcards <aggregateWithWildcards>` with aggregation ``multiply``.
"""
return aggregateWithWildcards(requestContext, seriesList, 'multiply', *position)
multiplySeriesWithWildcards.group = 'Combine'
multiplySeriesWithWildcards.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('position', ParamTypes.node, multiple=True),
]
multiplySeriesWithWildcards.aggregator = True
def aggregateWithWildcards(requestContext, seriesList, func, *positions):
"""
Call aggregator after inserting wildcards at the given position(s).
Example:
.. code-block:: none
&target=aggregateWithWildcards(host.cpu-[0-7].cpu-{user,system}.value, "sum", 1)
This would be the equivalent of
.. code-block:: none
&target=sumSeries(host.cpu-[0-7].cpu-user.value)&target=sumSeries(host.cpu-[0-7].cpu-system.value)
# or
&target=aggregate(host.cpu-[0-7].cpu-user.value,"sum")&target=aggregate(host.cpu-[0-7].cpu-system.value,"sum")
This function can be used with all aggregation functions supported by
:py:func:`aggregate <aggregate>`: ``average``, ``median``, ``sum``, ``min``, ``max``, ``diff``,
``stddev``, ``range`` & ``multiply``.
This complements :py:func:`groupByNodes <groupByNodes>` which takes a list of nodes that must match in each group.
"""
metaSeries = {}
keys = []
for series in seriesList:
key = '.'.join(map(lambda x: x[1], filter(lambda i: i[0] not in positions, enumerate(series.name.split('.')))))
if key not in metaSeries:
metaSeries[key] = [series]
keys.append(key)
else:
metaSeries[key].append(series)
for key in metaSeries.keys():
metaSeries[key] = aggregate(requestContext, metaSeries[key], func)[0]
metaSeries[key].name = key
return [ metaSeries[key] for key in keys ]
aggregateWithWildcards.group = 'Combine'
aggregateWithWildcards.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('func', ParamTypes.aggFunc, required=True),
Param('position', ParamTypes.node, multiple=True),
]
def diffSeries(requestContext, *seriesLists):
"""
Subtracts series 2 through n from series 1.
Example:
.. code-block:: none
&target=diffSeries(service.connections.total,service.connections.failed)
To diff a series and a constant, one should use offset instead of (or in
addition to) diffSeries
Example:
.. code-block:: none
&target=offset(service.connections.total,-5)
&target=offset(diffSeries(service.connections.total,service.connections.failed),-4)
This is an alias for :py:func:`aggregate <aggregate>` with aggregation ``diff``.
"""
return aggregate(requestContext, seriesLists, 'diff')
diffSeries.group = 'Combine'
diffSeries.params = [
Param('seriesLists', ParamTypes.seriesList, required=True, multiple=True),
]
diffSeries.aggregator = True
def diffSeriesLists(requestContext, seriesListFirstPos, seriesListSecondPos):
"""
Iterates over a two lists and subtracts series lists 2 through n from series 1
list1[0] to list2[0], list1[1] to list2[1] and so on.
The lists will need to be the same length
Example:
.. code-block:: none
&target=diffSeriesLists(mining.{carbon,graphite,diamond}.extracted,mining.{carbon,graphite,diamond}.shipped)
An example above would be the same as running :py:func:`diffSeries <diffSeries>` for each member of the list:
.. code-block:: none
?target=diffSeries(mining.carbon.extracted,mining.carbon.shipped)
&target=diffSeries(mining.graphite.extracted,mining.graphite.shipped)
&target=diffSeries(mining.diamond.extracted,mining.diamond.shipped)
This is an alias for :py:func:`aggregateSeriesLists <aggregateSeriesLists>` with aggregation ``diff``.
"""
return aggregateSeriesLists(requestContext, seriesListFirstPos, seriesListSecondPos, 'diff')
diffSeriesLists.group = 'Combine'
diffSeriesLists.params = [
Param('seriesListFirstPos', ParamTypes.seriesList, required=True),
Param('seriesListSecondPos', ParamTypes.seriesList, required=True),
]
diffSeriesLists.aggregator = True
def averageSeries(requestContext, *seriesLists):
"""
Short Alias: avg()
Takes one metric or a wildcard seriesList.
Draws the average value of all metrics passed at each time.
Example:
.. code-block:: none
&target=averageSeries(company.server.*.threads.busy)
This is an alias for :py:func:`aggregate <aggregate>` with aggregation ``average``.
"""
return aggregate(requestContext, seriesLists, 'average')
averageSeries.group = 'Combine'
averageSeries.params = [
Param('seriesLists', ParamTypes.seriesList, required=True, multiple=True),
]
averageSeries.aggregator = True
def stddevSeries(requestContext, *seriesLists):
"""
Takes one metric or a wildcard seriesList.
Draws the standard deviation of all metrics passed at each time.
Example:
.. code-block:: none
&target=stddevSeries(company.server.*.threads.busy)
This is an alias for :py:func:`aggregate <aggregate>` with aggregation ``stddev``.
"""
return aggregate(requestContext, seriesLists, 'stddev')
stddevSeries.group = 'Combine'
stddevSeries.params = [
Param('seriesLists', ParamTypes.seriesList, required=True, multiple=True),
]
stddevSeries.aggregator = True
def minSeries(requestContext, *seriesLists):
"""
Takes one metric or a wildcard seriesList.
For each datapoint from each metric passed in, pick the minimum value and graph it.
Example:
.. code-block:: none
&target=minSeries(Server*.connections.total)
This is an alias for :py:func:`aggregate <aggregate>` with aggregation ``min``.
"""
return aggregate(requestContext, seriesLists, 'min')
minSeries.group = 'Combine'
minSeries.params = [
Param('seriesLists', ParamTypes.seriesList, required=True, multiple=True),
]
minSeries.aggregator = True
def maxSeries(requestContext, *seriesLists):
"""
Takes one metric or a wildcard seriesList.
For each datapoint from each metric passed in, pick the maximum value and graph it.
Example:
.. code-block:: none
&target=maxSeries(Server*.connections.total)
This is an alias for :py:func:`aggregate <aggregate>` with aggregation ``max``.
"""
return aggregate(requestContext, seriesLists, 'max')
maxSeries.group = 'Combine'
maxSeries.params = [
Param('seriesLists', ParamTypes.seriesList, required=True, multiple=True),
]
maxSeries.aggregator = True
def rangeOfSeries(requestContext, *seriesLists):
"""
Takes a wildcard seriesList.
Distills down a set of inputs into the range of the series
Example:
.. code-block:: none
&target=rangeOfSeries(Server*.connections.total)
This is an alias for :py:func:`aggregate <aggregate>` with aggregation ``rangeOf``.
"""
return aggregate(requestContext, seriesLists, 'rangeOf')
rangeOfSeries.group = 'Combine'
rangeOfSeries.params = [
Param('seriesLists', ParamTypes.seriesList, required=True, multiple=True),
]
rangeOfSeries.aggregator = True
def percentileOfSeries(requestContext, seriesList, n, interpolate=False):
"""
percentileOfSeries returns a single series which is composed of the n-percentile
values taken across a wildcard series at each point. Unless `interpolate` is
set to True, percentile values are actual values contained in one of the
supplied series.
"""
if n <= 0:
raise InputParameterError('The requested percent is required to be greater than 0')
# if seriesList is empty then just short-circuit
if not seriesList:
return []
name = 'percentileOfSeries(%s,%g)' % (seriesList[0].pathExpression, n)
(start, end, step) = normalize([seriesList])[1:]
values = [ _getPercentile(row, n, interpolate) for row in izip_longest(*seriesList) ]
resultSeries = TimeSeries(name, start, end, step, values, xFilesFactor=requestContext.get('xFilesFactor'))
return [resultSeries]
percentileOfSeries.group = 'Combine'
percentileOfSeries.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.float, required=True),
Param('interpolate', ParamTypes.boolean, default=False),
]
def keepLastValue(requestContext, seriesList, limit = INF):
"""
Takes one metric or a wildcard seriesList, and optionally a limit to the number of 'None' values to skip over.
Continues the line with the last received value when gaps ('None' values) appear in your data, rather than breaking your line.
Example:
.. code-block:: none
&target=keepLastValue(Server01.connections.handled)
&target=keepLastValue(Server01.connections.handled, 10)
"""
for series in seriesList:
series.name = "keepLastValue(%s)" % (series.name)
series.pathExpression = series.name
consecutiveNones = 0
lastVal = None
for i,value in enumerate(series):
if value is None:
consecutiveNones += 1
else:
if 0 < consecutiveNones <= limit and lastVal is not None:
# If a non-None value is seen before the limit of Nones is hit,
# backfill all the missing datapoints with the last known value.
for index in range(i - consecutiveNones, i):
series[index] = lastVal
consecutiveNones = 0
lastVal = value
# If the series ends with some None values, try to backfill a bit to cover it.
if 0 < consecutiveNones <= limit and lastVal is not None:
for index in range(len(series) - consecutiveNones, len(series)):
series[index] = lastVal
return seriesList
keepLastValue.group = 'Transform'
keepLastValue.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('limit', ParamTypes.intOrInf, default=INF),
]
def interpolate(requestContext, seriesList, limit = INF):
"""
Takes one metric or a wildcard seriesList, and optionally a limit to the number of 'None' values to skip over.
Continues the line with the last received value when gaps ('None' values) appear in your data, rather than breaking your line.
Example:
.. code-block:: none
&target=interpolate(Server01.connections.handled)
&target=interpolate(Server01.connections.handled, 10)
"""
for series in seriesList:
series.name = "interpolate(%s)" % (series.name)
series.pathExpression = series.name
consecutiveNones = 0
for i,value in enumerate(series):
series[i] = value
# No 'keeping' can be done on the first value because we have no idea
# what came before it.
if i == 0:
continue
if value is None:
consecutiveNones += 1
elif consecutiveNones == 0: # have a value but no need to interpolate
continue
elif series[i - consecutiveNones - 1] is None: # have a value but can't interpolate: reset count
consecutiveNones = 0
continue
else: # have a value and can interpolate
# If a non-None value is seen before the limit of Nones is hit,
# backfill all the missing datapoints with the last known value.
if 0 < consecutiveNones <= limit:
for index in range(i - consecutiveNones, i):
series[index] = series[i - consecutiveNones - 1] + (index - (i - consecutiveNones -1)) * (value - series[i - consecutiveNones - 1]) / (consecutiveNones + 1)
consecutiveNones = 0
# If the series ends with some None values, try to backfill a bit to cover it.
# if 0 < consecutiveNones < limit:
# for index in xrange(len(series) - consecutiveNones, len(series)):
# series[index] = series[len(series) - consecutiveNones - 1]
return seriesList
interpolate.group = 'Transform'
interpolate.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('limit', ParamTypes.intOrInf, default=INF),
]
def changed(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
Output 1 when the value changed, 0 when null or the same
Example:
.. code-block:: none
&target=changed(Server01.connections.handled)
"""
for series in seriesList:
series.name = "changed(%s)" % (series.name)
series.pathExpression = series.name
previous = None
for i,value in enumerate(series):
if previous is None:
previous = value
series[i] = 0
elif value is not None and previous != value:
series[i] = 1
previous = value
else:
series[i] = 0
return seriesList
changed.group = 'Special'
changed.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def asPercent(requestContext, seriesList, total=None, *nodes):
"""
Calculates a percentage of the total of a wildcard series. If `total` is specified,
each series will be calculated as a percentage of that total. If `total` is not specified,
the sum of all points in the wildcard series will be used instead.
A list of nodes can optionally be provided, if so they will be used to match series with their
corresponding totals following the same logic as :py:func:`groupByNodes <groupByNodes>`.
When passing `nodes` the `total` parameter may be a series list or `None`. If it is `None` then
for each series in `seriesList` the percentage of the sum of series in that group will be returned.
When not passing `nodes`, the `total` parameter may be a single series, reference the same number
of series as `seriesList` or be a numeric value.
Example:
.. code-block:: none
# Server01 connections failed and succeeded as a percentage of Server01 connections attempted
&target=asPercent(Server01.connections.{failed,succeeded}, Server01.connections.attempted)
# For each server, its connections failed as a percentage of its connections attempted
&target=asPercent(Server*.connections.failed, Server*.connections.attempted)
# For each server, its connections failed and succeeded as a percentage of its connections attemped
&target=asPercent(Server*.connections.{failed,succeeded}, Server*.connections.attempted, 0)
# apache01.threads.busy as a percentage of 1500
&target=asPercent(apache01.threads.busy,1500)
# Server01 cpu stats as a percentage of its total
&target=asPercent(Server01.cpu.*.jiffies)
# cpu stats for each server as a percentage of its total
&target=asPercent(Server*.cpu.*.jiffies, None, 0)
When using `nodes`, any series or totals that can't be matched will create output series with
names like ``asPercent(someSeries,MISSING)`` or ``asPercent(MISSING,someTotalSeries)`` and all
values set to None. If desired these series can be filtered out by piping the result through
``|exclude("MISSING")`` as shown below:
.. code-block:: none
&target=asPercent(Server{1,2}.memory.used,Server{1,3}.memory.total,0)
# will produce 3 output series:
# asPercent(Server1.memory.used,Server1.memory.total) [values will be as expected]
# asPercent(Server2.memory.used,MISSING) [all values will be None]
# asPercent(MISSING,Server3.memory.total) [all values will be None]
&target=asPercent(Server{1,2}.memory.used,Server{1,3}.memory.total,0)|exclude("MISSING")
# will produce 1 output series:
# asPercent(Server1.memory.used,Server1.memory.total) [values will be as expected]
Each node may be an integer referencing a node in the series name or a string identifying a tag.
.. note::
When `total` is a seriesList, specifying `nodes` to match series with the corresponding total
series will increase reliability.
"""
normalize([seriesList])
xFilesFactor=requestContext.get('xFilesFactor')
# if nodes are specified, use them to match series & total
if nodes:
keys = []
# group series together by key
metaSeries = {}
for series in seriesList:
key = aggKey(series, nodes)
if key not in metaSeries:
metaSeries[key] = [series]
keys.append(key)
else:
metaSeries[key].append(series)
# make list of totals
totalSeries = {}
# no total seriesList was specified, sum the values for each group of series
if total is None:
for key in keys:
if len(metaSeries[key]) == 1:
totalSeries[key] = metaSeries[key][0]
else:
name = 'sumSeries(%s)' % formatPathExpressions(metaSeries[key])
(seriesList,start,end,step) = normalize([metaSeries[key]])
totalValues = [ safe.safeSum(row) for row in izip_longest(*metaSeries[key]) ]
totalSeries[key] = TimeSeries(name,start,end,step,totalValues,xFilesFactor=xFilesFactor)
# total seriesList was specified, sum the values for each group of totals
elif isinstance(total, list):
for series in total:
key = aggKey(series, nodes)
if key not in totalSeries:
totalSeries[key] = [series]
if key not in keys:
keys.append(key)
else:
totalSeries[key].append(series)
for key in totalSeries.keys():
if len(totalSeries[key]) == 1:
totalSeries[key] = totalSeries[key][0]
else:
name = 'sumSeries(%s)' % formatPathExpressions(totalSeries[key])
(seriesList,start,end,step) = normalize([totalSeries[key]])
totalValues = [ safe.safeSum(row) for row in izip_longest(*totalSeries[key]) ]
totalSeries[key] = TimeSeries(name,start,end,step,totalValues,xFilesFactor=xFilesFactor)
# trying to use nodes with a total value, which isn't supported because it has no effect
else:
raise InputParameterError('total must be None or a seriesList')
resultList = []
for key in keys:
# no series, must have total only
if key not in metaSeries:
series2 = totalSeries[key]
name = "asPercent(%s,%s)" % ('MISSING', series2.name)
resultValues = [ None for v1 in series2 ]
resultSeries = TimeSeries(name,start,end,step,resultValues,xFilesFactor=xFilesFactor)
resultList.append(resultSeries)
continue
for series1 in metaSeries[key]:
# no total
if key not in totalSeries:
name = "asPercent(%s,%s)" % (series1.name, 'MISSING')
resultValues = [ None for v1 in series1 ]
# series and total
else:
series2 = totalSeries[key]
name = "asPercent(%s,%s)" % (series1.name, series2.name)
(seriesList,start,end,step) = normalize([(series1, series2)])
resultValues = [ safe.safeMul(safe.safeDiv(v1, v2), 100.0) for v1,v2 in izip_longest(series1,series2) ]
resultSeries = TimeSeries(name,start,end,step,resultValues,xFilesFactor=xFilesFactor)
resultList.append(resultSeries)
return resultList
if total is None:
totalValues = [ safe.safeSum(row) for row in izip_longest(*seriesList) ]
totalText = "sumSeries(%s)" % formatPathExpressions(seriesList)
elif type(total) is list:
if len(total) != 1 and len(total) != len(seriesList):
raise InputParameterError("asPercent second argument must be missing, a single digit, reference exactly 1 series or reference the same number of series as the first argument")
if len(total) == 1:
normalize([seriesList, total])
totalValues = total[0]
totalText = totalValues.name
else:
totalValues = [total] * len(seriesList[0])
totalText = str(total)
resultList = []
if type(total) is list and len(total) == len(seriesList):
for series1, series2 in matchSeries(seriesList, total):
name = "asPercent(%s,%s)" % (series1.name,series2.name)
(seriesList,start,end,step) = normalize([(series1, series2)])
resultValues = [ safe.safeMul(safe.safeDiv(v1, v2), 100.0) for v1,v2 in izip_longest(series1,series2) ]
resultSeries = TimeSeries(name,start,end,step,resultValues,xFilesFactor=xFilesFactor)
resultList.append(resultSeries)
else:
for series in seriesList:
resultValues = [ safe.safeMul(safe.safeDiv(val, totalVal), 100.0) for val,totalVal in izip_longest(series,totalValues) ]
name = "asPercent(%s,%s)" % (series.name, totalText or series.pathExpression)
resultSeries = TimeSeries(name,series.start,series.end,series.step,resultValues,xFilesFactor=xFilesFactor)
resultList.append(resultSeries)
return resultList
asPercent.group = 'Combine'
asPercent.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('total', ParamTypes.any),
Param('nodes', ParamTypes.nodeOrTag, multiple=True),
]
asPercent.aggregator = True
def divideSeriesLists(requestContext, dividendSeriesList, divisorSeriesList):
"""
Iterates over a two lists and divides list1[0] by list2[0], list1[1] by list2[1] and so on.
The lists need to be the same length
"""
if len(dividendSeriesList) != len(divisorSeriesList):
raise InputParameterError("dividendSeriesList and divisorSeriesList argument must have equal length")
results = []
for i in range(0, len(dividendSeriesList)):
dividendSeries = dividendSeriesList[i]
divisorSeries = divisorSeriesList[i]
name = "divideSeries(%s,%s)" % (dividendSeries.name, divisorSeries.name)
bothSeries = (dividendSeries, divisorSeries)
step = reduce(lcm,[s.step for s in bothSeries])
for s in bothSeries:
s.consolidate( step // s.step )
start = min([s.start for s in bothSeries])
end = max([s.end for s in bothSeries])
end -= (end - start) % step
values = ( safe.safeDiv(v1,v2) for v1,v2 in izip_longest(*bothSeries) )
quotientSeries = TimeSeries(name, start, end, step, values, xFilesFactor=requestContext.get('xFilesFactor'))
results.append(quotientSeries)
return results
divideSeriesLists.group = 'Combine'
divideSeriesLists.params = [
Param('dividendSeriesList', ParamTypes.seriesList, required=True),
Param('divisorSeriesList', ParamTypes.seriesList, required=True),
]
def divideSeries(requestContext, dividendSeriesList, divisorSeries):
"""
Takes a dividend metric and a divisor metric and draws the division result.
A constant may *not* be passed. To divide by a constant, use the scale()
function (which is essentially a multiplication operation) and use the inverse
of the dividend. (Division by 8 = multiplication by 1/8 or 0.125)
Example:
.. code-block:: none
&target=divideSeries(Series.dividends,Series.divisors)
"""
if len(divisorSeries) == 0:
for series in dividendSeriesList:
series.name = "divideSeries(%s,MISSING)" % series.name
series.pathExpression = series.name
for i in range(len(series)):
series[i] = None
return dividendSeriesList
if len(divisorSeries) > 1:
raise InputParameterError("divideSeries second argument must reference exactly 1 series (got {0})".format(len(divisorSeries)))
divisorSeries = divisorSeries[0]
results = []
for dividendSeries in dividendSeriesList:
name = "divideSeries(%s,%s)" % (dividendSeries.name, divisorSeries.name)
bothSeries = (dividendSeries, divisorSeries)
step = reduce(lcm,[s.step for s in bothSeries])
for s in bothSeries:
s.consolidate( step // s.step )
start = min([s.start for s in bothSeries])
end = max([s.end for s in bothSeries])
end -= (end - start) % step
values = ( safe.safeDiv(v1,v2) for v1,v2 in izip_longest(*bothSeries) )
quotientSeries = TimeSeries(name, start, end, step, values, xFilesFactor=requestContext.get('xFilesFactor'))
results.append(quotientSeries)
return results
divideSeries.group = 'Combine'
divideSeries.params = [
Param('dividendSeriesList', ParamTypes.seriesList, required=True),
Param('divisorSeries', ParamTypes.seriesList, required=True),
]
def multiplySeries(requestContext, *seriesLists):
"""
Takes two or more series and multiplies their points. A constant may not be
used. To multiply by a constant, use the scale() function.
Example:
.. code-block:: none
&target=multiplySeries(Series.dividends,Series.divisors)
This is an alias for :py:func:`aggregate <aggregate>` with aggregation ``multiply``.
"""
# special handling for legacy multiplySeries behavior with a single series
if len(seriesLists) == 1 and len(seriesLists[0]) == 1:
return seriesLists[0]
return aggregate(requestContext, seriesLists, 'multiply')
multiplySeries.group = 'Combine'
multiplySeries.params = [
Param('seriesLists', ParamTypes.seriesList, required=True, multiple=True),
]
multiplySeries.aggregator = True
def multiplySeriesLists(requestContext, seriesListFirstPos, seriesListSecondPos):
"""
Iterates over a two lists and subtracts series lists 2 through n from series 1
list1[0] to list2[0], list1[1] to list2[1] and so on.
The lists will need to be the same length
Example:
.. code-block:: none
&target=multiplySeriesLists(mining.{carbon,graphite,diamond}.extracted,mining.{carbon,graphite,diamond}.shipped)
An example above would be the same as running :py:func:`multiplySeries <multiplySeries>` for each member of the list:
.. code-block:: none
?target=multiplySeries(mining.carbon.extracted,mining.carbon.shipped)
&target=multiplySeries(mining.graphite.extracted,mining.graphite.shipped)
&target=multiplySeries(mining.diamond.extracted,mining.diamond.shipped)
This is an alias for :py:func:`aggregateSeriesLists <aggregateSeriesLists>` with aggregation ``multiply``.
"""
return aggregateSeriesLists(requestContext, seriesListFirstPos, seriesListSecondPos, 'multiply')
multiplySeriesLists.group = 'Combine'
multiplySeriesLists.params = [
Param('seriesListFirstPos', ParamTypes.seriesList, required=True),
Param('seriesListSecondPos', ParamTypes.seriesList, required=True),
]
multiplySeriesLists.aggregator = True
def weightedAverage(requestContext, seriesListAvg, seriesListWeight, *nodes):
"""
Takes a series of average values and a series of weights and
produces a weighted average for all values.
The corresponding values should share one or more zero-indexed nodes and/or tags.
Example:
.. code-block:: none
&target=weightedAverage(*.transactions.mean,*.transactions.count,0)
Each node may be an integer referencing a node in the series name or a string identifying a tag.
"""
sortedSeries={}
if len(seriesListAvg) != len(seriesListWeight):
raise InputParameterError('weightedAverage must receive the same number of series for seriesListAvg and seriesListWeight but received respectively %d and %d' % (len(seriesListAvg), len(seriesListWeight)))
for seriesAvg, seriesWeight in izip_longest(seriesListAvg , seriesListWeight):
key = aggKey(seriesAvg, nodes)
if key not in sortedSeries:
sortedSeries[key]={}
sortedSeries[key]['avg']=seriesAvg
key = aggKey(seriesWeight, nodes)
if key not in sortedSeries:
sortedSeries[key]={}
sortedSeries[key]['weight']=seriesWeight
productList = []
for key in sortedSeries.keys():
if 'weight' not in sortedSeries[key]:
continue
if 'avg' not in sortedSeries[key]:
continue
seriesWeight = sortedSeries[key]['weight']
seriesAvg = sortedSeries[key]['avg']
productValues = [ safe.safeMul(val1, val2) for val1,val2 in izip_longest(seriesAvg,seriesWeight) ]
name='product(%s,%s)' % (seriesWeight.name, seriesAvg.name)
productSeries = TimeSeries(name,seriesAvg.start,seriesAvg.end,seriesAvg.step,productValues,xFilesFactor=requestContext.get('xFilesFactor'))
productList.append(productSeries)
if not productList:
return []
sumProducts=sumSeries(requestContext, productList)[0]
sumWeights=sumSeries(requestContext, seriesListWeight)[0]
resultValues = [ safe.safeDiv(val1, val2) for val1,val2 in izip_longest(sumProducts,sumWeights) ]
name = "weightedAverage(%s, %s, %s)" % (','.join(sorted(set(s.pathExpression for s in seriesListAvg))) ,','.join(sorted(set(s.pathExpression for s in seriesListWeight))), ','.join(map(str,nodes)))
resultSeries = TimeSeries(name,sumProducts.start,sumProducts.end,sumProducts.step,resultValues,xFilesFactor=requestContext.get('xFilesFactor'))
return [resultSeries]
weightedAverage.group = 'Combine'
weightedAverage.params = [
Param('seriesListAvg', ParamTypes.seriesList, required=True),
Param('seriesListWeight', ParamTypes.seriesList, required=True),
Param('nodes', ParamTypes.nodeOrTag, multiple=True),
]
intOrIntervalSuggestions = [5, 7, 10, '1min', '5min', '10min', '30min', '1hour']
def movingWindow(requestContext, seriesList, windowSize, func='average', xFilesFactor=None):
"""
Graphs a moving window function of a metric (or metrics) over a fixed number of
past points, or a time interval.
Takes one metric or a wildcard seriesList, a number N of datapoints
or a quoted string with a length of time like '1hour' or '5min' (See ``from /
until`` in the :doc:`Render API <render_api>` for examples of time formats), a function to apply to the points
in the window to produce the output, and an xFilesFactor value to specify how many points in the
window must be non-null for the output to be considered valid. Graphs the
output of the function for the preceeding datapoints for each point on the graph.
Example:
.. code-block:: none
&target=movingWindow(Server.instance01.threads.busy,10)
&target=movingWindow(Server.instance*.threads.idle,'5min','median',0.5)
.. note::
`xFilesFactor` follows the same semantics as in Whisper storage schemas. Setting it to 0 (the
default) means that only a single value in a given interval needs to be non-null, setting it to
1 means that all values in the interval must be non-null. A setting of 0.5 means that at least
half the values in the interval must be non-null.
"""
if not seriesList:
return []
if isinstance(windowSize, six.string_types):
delta = parseTimeOffset(windowSize)
previewSeconds = abs(delta.seconds + (delta.days * 86400))
else:
previewSeconds = max([s.step for s in seriesList]) * int(windowSize)
consolidateFunc = getAggFunc(func)
# ignore original data and pull new, including our preview
# data from earlier is needed to calculate the early results
newContext = requestContext.copy()
newContext['prefetch'] = {}
newContext['startTime'] = requestContext['startTime'] - timedelta(seconds=previewSeconds)
previewList = evaluateTarget(newContext, requestContext['args'][0])
result = []
tagName = 'moving' + func.capitalize()
for series in previewList:
if isinstance(windowSize, six.string_types):
newName = '%s(%s,"%s")' % (tagName, series.name, windowSize)
windowPoints = previewSeconds // series.step
else:
newName = '%s(%s,%s)' % (tagName, series.name, windowSize)
windowPoints = int(windowSize)
series.tags[tagName] = windowSize
newSeries = series.copy(name=newName, start=series.start + previewSeconds, values=[])
effectiveXFF = xFilesFactor if xFilesFactor is not None else series.xFilesFactor
for i in range(windowPoints + 1, len(series) + 1):
nonNull = [v for v in series[i - windowPoints:i] if v is not None]
if nonNull and xff(len(nonNull), windowPoints, effectiveXFF):
val = consolidateFunc(nonNull)
else:
val = None
newSeries.append(val)
result.append(newSeries)
return result
movingWindow.group = 'Calculate'
movingWindow.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('windowSize', ParamTypes.intOrInterval, required=True, suggestions=intOrIntervalSuggestions),
Param('func', ParamTypes.aggFunc, default='average'),
Param('xFilesFactor', ParamTypes.float),
]
def exponentialMovingAverage(requestContext, seriesList, windowSize):
"""
Takes a series of values and a window size and produces an exponential moving
average utilizing the following formula:
.. code-block:: none
ema(current) = constant * (Current Value) + (1 - constant) * ema(previous)
The Constant is calculated as:
.. code-block:: none
constant = 2 / (windowSize + 1)
The first period EMA uses a simple moving average for its value.
Example:
.. code-block:: none
&target=exponentialMovingAverage(*.transactions.count, 10)
&target=exponentialMovingAverage(*.transactions.count, '-10s')
"""
# EMA = C * (current_value) + (1 - C) + EMA
# C = 2 / (windowSize + 1)
# The following was copied from movingAverage, and altered for ema
if not seriesList:
return []
# set previewSeconds and constant based on windowSize string or integer
if isinstance(windowSize, six.string_types):
delta = parseTimeOffset(windowSize)
previewSeconds = abs(delta.seconds + (delta.days * 86400))
constant = (float(2) / (int(previewSeconds) + 1))
else:
previewSeconds = max([s.step for s in seriesList]) * int(windowSize)
constant = (float(2) / (int(windowSize) + 1))
# ignore original data and pull new, including our preview
# data from earlier is needed to calculate the early results
newContext = requestContext.copy()
newContext['prefetch'] = {}
newContext['startTime'] = requestContext['startTime'] - timedelta(seconds=previewSeconds)
previewList = evaluateTarget(newContext, requestContext['args'][0])
result = []
for series in previewList:
if isinstance(windowSize, six.string_types):
newName = 'exponentialMovingAverage(%s,"%s")' % (series.name, windowSize)
windowPoints = previewSeconds // series.step
else:
newName = "exponentialMovingAverage(%s,%s)" % (series.name, windowSize)
windowPoints = int(windowSize)
series.tags['exponentialMovingAverage'] = windowSize
newSeries = series.copy(name=newName, start=series.start + previewSeconds, values=[])
ema = safe.safeAvg(series[:windowPoints]) or 0
newSeries.append(round(ema, 6))
for i in range(windowPoints, len(series)):
if series[i] is not None:
ema = constant * series[i] + (1 - constant) * ema
newSeries.append(round(ema, 6))
else:
newSeries.append(None)
result.append(newSeries)
return result
exponentialMovingAverage.group = 'Calculate'
exponentialMovingAverage.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('windowSize', ParamTypes.intOrInterval, required=True, suggestions=intOrIntervalSuggestions),
]
def movingMedian(requestContext, seriesList, windowSize, xFilesFactor=None):
"""
Graphs the moving median of a metric (or metrics) over a fixed number of
past points, or a time interval.
Takes one metric or a wildcard seriesList followed by a number N of datapoints
or a quoted string with a length of time like '1hour' or '5min' (See ``from /
until`` in the :doc:`Render API <render_api>` for examples of time formats), and an xFilesFactor value to specify
how many points in the window must be non-null for the output to be considered valid. Graphs the
median of the preceeding datapoints for each point on the graph.
Example:
.. code-block:: none
&target=movingMedian(Server.instance01.threads.busy,10)
&target=movingMedian(Server.instance*.threads.idle,'5min')
"""
return movingWindow(requestContext, seriesList, windowSize, 'median', xFilesFactor)
movingMedian.group = 'Calculate'
movingMedian.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('windowSize', ParamTypes.intOrInterval, required=True, suggestions=intOrIntervalSuggestions),
Param('xFilesFactor', ParamTypes.float),
]
def scale(requestContext, seriesList, factor):
"""
Takes one metric or a wildcard seriesList followed by a constant, and multiplies the datapoint
by the constant provided at each point.
Example:
.. code-block:: none
&target=scale(Server.instance01.threads.busy,10)
&target=scale(Server.instance*.threads.busy,10)
"""
for series in seriesList:
series.tags['scale'] = factor
series.name = "scale(%s,%g)" % (series.name,float(factor))
series.pathExpression = series.name
for i,value in enumerate(series):
series[i] = safe.safeMul(value,factor)
return seriesList
scale.group = 'Transform'
scale.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('factor', ParamTypes.float, required=True),
]
def scaleToSeconds(requestContext, seriesList, seconds):
"""
Takes one metric or a wildcard seriesList and returns "value per seconds" where
seconds is a last argument to this functions.
Useful in conjunction with derivative or integral function if you want
to normalize its result to a known resolution for arbitrary retentions
"""
for series in seriesList:
series.tags['scaleToSeconds'] = seconds
series.name = "scaleToSeconds(%s,%d)" % (series.name,seconds)
series.pathExpression = series.name
factor = seconds / series.step
for i,value in enumerate(series):
if value is not None:
# Division long by float cause OverflowError
try:
series[i] = round(value * factor, 6)
except OverflowError:
series[i] = (value // series.step) * seconds
return seriesList
scaleToSeconds.group = 'Transform'
scaleToSeconds.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('seconds', ParamTypes.float, required=True),
]
def exp(requestContext, seriesList):
"""
Raise e to the power of the datapoint,
where e = 2.718281... is the base of natural logarithms.
Example:
.. code-block:: none
&target=exp(Server.instance01.threads.busy)
"""
for series in seriesList:
series.tags['exp'] = 'e'
series.name = "exp(%s)" % (series.name)
series.pathExpression = series.name
for i, value in enumerate(series):
series[i] = safe.safeExp(value)
return seriesList
exp.group = 'Transform'
exp.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def add(requestContext, seriesList, constant):
"""
Takes one metric or a wildcard seriesList followed by a constant, and adds the
constant to each datapoint. Also works for negative numbers.
Example:
.. code-block:: none
&target=add(Server.instance01.threads.busy, 10)
&target=add(Server.instance*.threads.busy, 10)
"""
for series in seriesList:
series.tags['add'] = constant
series.name = "add(%s,%d)" % (series.name, constant)
series.pathExpression = series.name
for i, value in enumerate(series):
try:
series[i] = value + constant
except TypeError:
series[i] = None
return seriesList
add.group = 'Transform'
add.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('constant', ParamTypes.float, required=True),
]
def sigmoid(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList and applies the sigmoid
function `1 / (1 + exp(-x))` to each datapoint.
Example:
.. code-block:: none
&target=sigmoid(Server.instance01.threads.busy)
&target=sigmoid(Server.instance*.threads.busy)
"""
for series in seriesList:
series.tags['sigmoid'] = 'sigmoid'
series.name = "sigmoid(%s)" % series.name
series.pathExpression = series.name
for i, value in enumerate(series):
try:
log.info(value)
series[i] = 1 / (1 + safe.safeExp(-value))
except (TypeError, ValueError, ZeroDivisionError):
series[i] = None
return seriesList
sigmoid.group = 'Transform'
sigmoid.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def logit(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList and applies the logit
function `log(x / (1 - x))` to each datapoint.
Example:
.. code-block:: none
&target=logit(Server.instance01.threads.busy)
&target=logit(Server.instance*.threads.busy)
"""
for series in seriesList:
series.tags['logit'] = 'logit'
series.name = "logit(%s)" % series.name
series.pathExpression = series.name
for i, value in enumerate(series):
try:
series[i] = math.log(value / (1 - value))
except (TypeError, ValueError, ZeroDivisionError):
series[i] = None
return seriesList
logit.group = 'Transform'
logit.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def pow(requestContext, seriesList, factor):
"""
Takes one metric or a wildcard seriesList followed by a constant, and raises the datapoint
by the power of the constant provided at each point.
Example:
.. code-block:: none
&target=pow(Server.instance01.threads.busy,10)
&target=pow(Server.instance*.threads.busy,10)
"""
for series in seriesList:
series.tags['pow'] = factor
series.name = "pow(%s,%g)" % (series.name, float(factor))
series.pathExpression = series.name
for i,value in enumerate(series):
series[i] = safe.safePow(value, factor)
return seriesList
pow.group = 'Transform'
pow.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('factor', ParamTypes.float, required=True),
]
def powSeries(requestContext, *seriesLists):
"""
Takes two or more series and pows their points. A constant line may be
used.
Example:
.. code-block:: none
&target=powSeries(Server.instance01.app.requests, Server.instance01.app.replies)
"""
try:
(seriesList, start, end, step) = normalize(seriesLists)
except NormalizeEmptyResultError:
return []
name = "powSeries(%s)" % ','.join([s.name for s in seriesList])
values = []
for row in izip_longest(*seriesList):
first = True
tmpVal = None
for element in row:
# If it is a first iteration - tmpVal needs to be element
if first:
tmpVal = element
first = False
else:
tmpVal = safe.safePow(tmpVal, element)
values.append(tmpVal)
series = TimeSeries(name,start,end,step,values,xFilesFactor=requestContext.get('xFilesFactor'))
return [series]
powSeries.group = 'Combine'
powSeries.params = [
Param('seriesList', ParamTypes.seriesList, required=True, multiple=True),
]
powSeries.aggregator = True
def squareRoot(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList, and computes the square root of each datapoint.
Example:
.. code-block:: none
&target=squareRoot(Server.instance01.threads.busy)
"""
for series in seriesList:
series.tags['squareRoot'] = 1
series.name = "squareRoot(%s)" % (series.name)
series.pathExpression = series.name
for i,value in enumerate(series):
series[i] = safe.safePow(value, 0.5)
return seriesList
squareRoot.group = 'Transform'
squareRoot.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def invert(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList, and inverts each datapoint (i.e. 1/x).
Example:
.. code-block:: none
&target=invert(Server.instance01.threads.busy)
"""
for series in seriesList:
series.tags['invert'] = 1
series.name = "invert(%s)" % (series.name)
series.pathExpression = series.name
for i,value in enumerate(series):
series[i] = safe.safePow(value, -1)
return seriesList
invert.group = 'Transform'
invert.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def absolute(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList and applies the mathematical abs function to each
datapoint transforming it to its absolute value.
Example:
.. code-block:: none
&target=absolute(Server.instance01.threads.busy)
&target=absolute(Server.instance*.threads.busy)
"""
for series in seriesList:
series.tags['absolute'] = 1
series.name = "absolute(%s)" % (series.name)
series.pathExpression = series.name
for i,value in enumerate(series):
series[i] = safe.safeAbs(value)
return seriesList
absolute.group = 'Transform'
absolute.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def offset(requestContext, seriesList, factor):
"""
Takes one metric or a wildcard seriesList followed by a constant, and adds the constant to
each datapoint.
Example:
.. code-block:: none
&target=offset(Server.instance01.threads.busy,10)
"""
for series in seriesList:
series.tags['offset'] = factor
series.name = "offset(%s,%g)" % (series.name,float(factor))
series.pathExpression = series.name
for i,value in enumerate(series):
if value is not None:
series[i] = value + factor
return seriesList
offset.group = 'Transform'
offset.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('factor', ParamTypes.float, required=True),
]
def offsetToZero(requestContext, seriesList):
"""
Offsets a metric or wildcard seriesList by subtracting the minimum
value in the series from each datapoint.
Useful to compare different series where the values in each series
may be higher or lower on average but you're only interested in the
relative difference.
An example use case is for comparing different round trip time
results. When measuring RTT (like pinging a server), different
devices may come back with consistently different results due to
network latency which will be different depending on how many
network hops between the probe and the device. To compare different
devices in the same graph, the network latency to each has to be
factored out of the results. This is a shortcut that takes the
fastest response (lowest number in the series) and sets that to zero
and then offsets all of the other datapoints in that series by that
amount. This makes the assumption that the lowest response is the
fastest the device can respond, of course the more datapoints that
are in the series the more accurate this assumption is.
Example:
.. code-block:: none
&target=offsetToZero(Server.instance01.responseTime)
&target=offsetToZero(Server.instance*.responseTime)
"""
for series in seriesList:
minimum = safe.safeMin(series)
series.tags['offsetToZero'] = minimum
series.name = "offsetToZero(%s)" % (series.name)
series.pathExpression = series.name
for i,value in enumerate(series):
if value is not None:
series[i] = value - minimum
return seriesList
offsetToZero.group = 'Transform'
offsetToZero.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def roundFunction(requestContext, seriesList, precision=None):
"""
Takes one metric or a wildcard seriesList optionally followed by a precision, and rounds each
datapoint to the specified precision.
Example:
.. code-block:: none
&target=round(Server.instance01.threads.busy)
&target=round(Server.instance01.threads.busy,2)
"""
for series in seriesList:
series.tags['round'] = precision or 0
if precision is None:
series.name = "round(%s)" % (series.name)
else:
series.name = "round(%s,%g)" % (series.name,int(precision))
series.pathExpression = series.name
for i,value in enumerate(series):
if value is not None:
series[i] = round(value, precision or 0)
return seriesList
roundFunction.group = 'Transform'
roundFunction.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('precision', ParamTypes.integer, default=0),
]
def movingAverage(requestContext, seriesList, windowSize, xFilesFactor=None):
"""
Graphs the moving average of a metric (or metrics) over a fixed number of
past points, or a time interval.
Takes one metric or a wildcard seriesList followed by a number N of datapoints
or a quoted string with a length of time like '1hour' or '5min' (See ``from /
until`` in the :doc:`Render API <render_api>` for examples of time formats), and an xFilesFactor value to specify
how many points in the window must be non-null for the output to be considered valid. Graphs the
average of the preceeding datapoints for each point on the graph.
Example:
.. code-block:: none
&target=movingAverage(Server.instance01.threads.busy,10)
&target=movingAverage(Server.instance*.threads.idle,'5min')
"""
return movingWindow(requestContext, seriesList, windowSize, 'average', xFilesFactor)
movingAverage.group = 'Calculate'
movingAverage.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('windowSize', ParamTypes.intOrInterval, required=True, suggestions=intOrIntervalSuggestions),
Param('xFilesFactor', ParamTypes.float),
]
def movingSum(requestContext, seriesList, windowSize, xFilesFactor=None):
"""
Graphs the moving sum of a metric (or metrics) over a fixed number of
past points, or a time interval.
Takes one metric or a wildcard seriesList followed by a number N of datapoints
or a quoted string with a length of time like '1hour' or '5min' (See ``from /
until`` in the :doc:`Render API <render_api>` for examples of time formats), and an xFilesFactor value to specify
how many points in the window must be non-null for the output to be considered valid. Graphs the
sum of the preceeding datapoints for each point on the graph.
Example:
.. code-block:: none
&target=movingSum(Server.instance01.requests,10)
&target=movingSum(Server.instance*.errors,'5min')
"""
return movingWindow(requestContext, seriesList, windowSize, 'sum', xFilesFactor)
movingSum.group = 'Calculate'
movingSum.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('windowSize', ParamTypes.intOrInterval, required=True, suggestions=intOrIntervalSuggestions),
Param('xFilesFactor', ParamTypes.float),
]
def movingMin(requestContext, seriesList, windowSize, xFilesFactor=None):
"""
Graphs the moving minimum of a metric (or metrics) over a fixed number of
past points, or a time interval.
Takes one metric or a wildcard seriesList followed by a number N of datapoints
or a quoted string with a length of time like '1hour' or '5min' (See ``from /
until`` in the :doc:`Render API <render_api>` for examples of time formats), and an xFilesFactor value to specify
how many points in the window must be non-null for the output to be considered valid. Graphs the
minimum of the preceeding datapoints for each point on the graph.
Example:
.. code-block:: none
&target=movingMin(Server.instance01.requests,10)
&target=movingMin(Server.instance*.errors,'5min')
"""
return movingWindow(requestContext, seriesList, windowSize, 'min', xFilesFactor)
movingMin.group = 'Calculate'
movingMin.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('windowSize', ParamTypes.intOrInterval, required=True, suggestions=intOrIntervalSuggestions),
Param('xFilesFactor', ParamTypes.float),
]
def movingMax(requestContext, seriesList, windowSize, xFilesFactor=None):
"""
Graphs the moving maximum of a metric (or metrics) over a fixed number of
past points, or a time interval.
Takes one metric or a wildcard seriesList followed by a number N of datapoints
or a quoted string with a length of time like '1hour' or '5min' (See ``from /
until`` in the :doc:`Render API <render_api>` for examples of time formats), and an xFilesFactor value to specify
how many points in the window must be non-null for the output to be considered valid. Graphs the
maximum of the preceeding datapoints for each point on the graph.
Example:
.. code-block:: none
&target=movingMax(Server.instance01.requests,10)
&target=movingMax(Server.instance*.errors,'5min')
"""
return movingWindow(requestContext, seriesList, windowSize, 'max', xFilesFactor)
movingMax.group = 'Calculate'
movingMax.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('windowSize', ParamTypes.intOrInterval, required=True, suggestions=intOrIntervalSuggestions),
Param('xFilesFactor', ParamTypes.float),
]
def cumulative(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
When a graph is drawn where width of the graph size in pixels is smaller than
the number of datapoints to be graphed, Graphite consolidates the values to
to prevent line overlap. The cumulative() function changes the consolidation
function from the default of 'average' to 'sum'. This is especially useful in
sales graphs, where fractional values make no sense and a 'sum' of consolidated
values is appropriate.
Alias for :func:`consolidateBy(series, 'sum') <graphite.render.functions.consolidateBy>`
.. code-block:: none
&target=cumulative(Sales.widgets.largeBlue)
"""
return consolidateBy(requestContext, seriesList, 'sum')
cumulative.group = 'Special'
cumulative.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def consolidateBy(requestContext, seriesList, consolidationFunc):
"""
Takes one metric or a wildcard seriesList and a consolidation function name.
Valid function names are 'sum', 'average'/'avg', 'min', 'max', 'first' & 'last'.
When a graph is drawn where width of the graph size in pixels is smaller than
the number of datapoints to be graphed, Graphite consolidates the values to
to prevent line overlap. The consolidateBy() function changes the consolidation
function from the default of 'average' to one of 'sum', 'max', 'min', 'first', or 'last'.
This is especially useful in sales graphs, where fractional values make no sense and a 'sum'
of consolidated values is appropriate.
.. code-block:: none
&target=consolidateBy(Sales.widgets.largeBlue, 'sum')
&target=consolidateBy(Servers.web01.sda1.free_space, 'max')
"""
for series in seriesList:
# datalib will throw an exception, so it's not necessary to validate here
series.consolidationFunc = consolidationFunc
series.tags['consolidateBy'] = consolidationFunc
series.name = 'consolidateBy(%s,"%s")' % (series.name, series.consolidationFunc)
series.pathExpression = series.name
return seriesList
consolidateBy.group = 'Special'
consolidateBy.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('consolidationFunc', ParamTypes.string, required=True, options=['sum', 'average', 'avg', 'avg_zero', 'min', 'max', 'first', 'last']),
]
def setXFilesFactor(requestContext, seriesList, xFilesFactor):
"""
Short form: xFilesFactor()
Takes one metric or a wildcard seriesList and an xFilesFactor value between 0 and 1
When a series needs to be consolidated, this sets the fraction of values in an interval that must
not be null for the consolidation to be considered valid. If there are not enough values then
None will be returned for that interval.
.. code-block:: none
&target=xFilesFactor(Sales.widgets.largeBlue, 0.5)
&target=Servers.web01.sda1.free_space|consolidateBy('max')|xFilesFactor(0.5)
The `xFilesFactor` set via this function is used as the default for all functions that accept an
`xFilesFactor` parameter, all functions that aggregate data across multiple series and/or
intervals, and `maxDataPoints <render_api.html#maxdatapoints>`_ consolidation.
A default for the entire render request can also be set using the
`xFilesFactor <render_api.html#xfilesfactor>`_ query parameter.
.. note::
`xFilesFactor` follows the same semantics as in Whisper storage schemas. Setting it to 0 (the
default) means that only a single value in a given interval needs to be non-null, setting it to
1 means that all values in the interval must be non-null. A setting of 0.5 means that at least
half the values in the interval must be non-null.
"""
requestContext['xFilesFactor'] = xFilesFactor
for series in seriesList:
series.xFilesFactor = xFilesFactor
series.tags['xFilesFactor'] = xFilesFactor
return seriesList
setXFilesFactor.group = 'Special'
setXFilesFactor.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('xFilesFactor', ParamTypes.float, required=True),
]
def derivative(requestContext, seriesList):
"""
This is the opposite of the integral function. This is useful for taking a
running total metric and calculating the delta between subsequent data points.
This function does not normalize for periods of time, as a true derivative would.
Instead see the perSecond() function to calculate a rate of change over time.
Example:
.. code-block:: none
&target=derivative(company.server.application01.ifconfig.TXPackets)
Each time you run ifconfig, the RX and TXPackets are higher (assuming there
is network traffic.) By applying the derivative function, you can get an
idea of the packets per minute sent or received, even though you're only
recording the total.
"""
results = []
for series in seriesList:
if settings.AUTOCOMPRESS_GAPS_IN_DERIVATIVE_FUNCTIONS:
series = _compressPeriodicGaps(series)
newValues = []
prev = None
for val in series:
if None in (prev,val):
newValues.append(None)
prev = val
continue
newValues.append(val - prev)
prev = val
series.tags['derivative'] = 1
newName = "derivative(%s)" % series.name
newSeries = series.copy(name=newName, values=newValues)
results.append(newSeries)
return results
derivative.group = 'Transform'
derivative.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def perSecond(requestContext, seriesList, maxValue=None, minValue=None):
"""
NonNegativeDerivative adjusted for the series time interval
This is useful for taking a running total metric and showing how many requests
per second were handled.
The optional ``minValue`` and ``maxValue`` parameters have the same
meaning as in ``nonNegativeDerivative``.
Example:
.. code-block:: none
&target=perSecond(company.server.application01.ifconfig.TXPackets)
Each time you run ifconfig, the RX and TXPackets are higher (assuming there
is network traffic.) By applying the perSecond function, you can get an
idea of the packets per second sent or received, even though you're only
recording the total.
"""
results = []
for series in seriesList:
if settings.AUTOCOMPRESS_GAPS_IN_DERIVATIVE_FUNCTIONS:
series = _compressPeriodicGaps(series)
newValues = []
prev = None
step = series.step
for val in series:
delta, prev = _nonNegativeDelta(val, prev, maxValue, minValue)
if delta is not None:
# Division long by float cause OverflowError
try:
newValues.append(round(delta / step, 6))
except OverflowError:
newValues.append(delta // step)
else:
newValues.append(None)
series.tags['perSecond'] = 1
newName = "perSecond(%s)" % series.name
newSeries = series.copy(name=newName, values=newValues)
results.append(newSeries)
return results
perSecond.group = 'Transform'
perSecond.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('maxValue', ParamTypes.float),
Param('minValue', ParamTypes.float),
]
def delay(requestContext, seriesList, steps):
"""
This shifts all samples later by an integer number of steps. This can be
used for custom derivative calculations, among other things. Note: this
will pad the early end of the data with None for every step shifted.
This complements other time-displacement functions such as timeShift and
timeSlice, in that this function is indifferent about the step intervals
being shifted.
Example:
.. code-block:: none
&target=divideSeries(server.FreeSpace,delay(server.FreeSpace,1))
This computes the change in server free space as a percentage of the previous
free space.
"""
results = []
for series in seriesList:
if steps < 0:
newValues = series[-steps:] + [None] * min(-steps, len(series))
else:
newValues = [None] * min(steps, len(series)) + series[:-steps]
series.tags['delay'] = steps
newName = "delay(%s,%d)" % (series.name, steps)
newSeries = series.copy(name=newName, values=newValues)
results.append(newSeries)
return results
delay.group = 'Transform'
delay.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('steps', ParamTypes.integer, required=True),
]
def integral(requestContext, seriesList):
"""
This will show the sum over time, sort of like a continuous addition function.
Useful for finding totals or trends in metrics that are collected per minute.
Example:
.. code-block:: none
&target=integral(company.sales.perMinute)
This would start at zero on the left side of the graph, adding the sales each
minute, and show the total sales for the time period selected at the right
side, (time now, or the time specified by '&until=').
"""
results = []
for series in seriesList:
newValues = []
current = 0.0
for val in series:
if val is None:
newValues.append(None)
else:
current += val
newValues.append(current)
series.tags['integral'] = 1
newName = "integral(%s)" % series.name
newSeries = series.copy(name=newName, values=newValues)
results.append(newSeries)
return results
integral.group = 'Transform'
integral.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def integralByInterval(requestContext, seriesList, intervalUnit):
"""
This will do the same as integral() funcion, except resetting the total to 0
at the given time in the parameter "from"
Useful for finding totals per hour/day/week/..
Example:
.. code-block:: none
&target=integralByInterval(company.sales.perMinute, "1d")&from=midnight-10days
This would start at zero on the left side of the graph, adding the sales each
minute, and show the evolution of sales per day during the last 10 days.
"""
intervalDuration = int(abs(deltaseconds(parseTimeOffset(intervalUnit))))
startTime = int(timestamp(requestContext['startTime']))
results = []
for series in seriesList:
newValues = []
currentTime = series.start # current time within series iteration
current = 0.0 # current accumulated value
for val in series:
# reset integral value if crossing an interval boundary
if (currentTime - startTime)//intervalDuration != (currentTime - startTime - series.step)//intervalDuration:
current = 0.0
if val is None:
# keep previous value since val can be None when resetting current to 0.0
newValues.append(current)
else:
current += val
newValues.append(current)
currentTime += series.step
series.tags['integralByInterval'] = intervalUnit
newName = "integralByInterval(%s,'%s')" % (series.name, intervalUnit)
newSeries = series.copy(name=newName, values=newValues)
results.append(newSeries)
return results
integralByInterval.group = 'Transform'
integralByInterval.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('intervalUnit', ParamTypes.string, required=True),
]
def nonNegativeDerivative(requestContext, seriesList, maxValue=None, minValue=None):
"""
Same as the derivative function above, but ignores datapoints that trend
down. Useful for counters that increase for a long time, then wrap or
reset. (Such as if a network interface is destroyed and recreated by unloading
and re-loading a kernel module, common with USB / WiFi cards.
By default, a null value is returned in place of negative datapoints. When
``maxValue`` is supplied, the missing value is computed as if the counter
had wrapped at ``maxValue``. When ``minValue`` is supplied, the missing
value is computed as if the counter had wrapped to ``minValue``.
Example:
.. code-block:: none
&target=nonNegativederivative(company.server.application01.ifconfig.TXPackets)
"""
results = []
for series in seriesList:
if settings.AUTOCOMPRESS_GAPS_IN_DERIVATIVE_FUNCTIONS:
series = _compressPeriodicGaps(series)
newValues = []
prev = None
for val in series:
delta, prev = _nonNegativeDelta(val, prev, maxValue, minValue)
newValues.append(delta)
series.tags['nonNegativeDerivative'] = 1
newName = "nonNegativeDerivative(%s)" % series.name
newSeries = series.copy(name=newName, values=newValues)
results.append(newSeries)
return results
nonNegativeDerivative.group = 'Transform'
nonNegativeDerivative.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('maxValue', ParamTypes.float),
Param('minValue', ParamTypes.float),
]
def _nonNegativeDelta(val, prev, maxValue, minValue):
# ignore values larger than maxValue
if maxValue is not None and val > maxValue:
return None, None
if minValue is not None and val < minValue:
return None, None
# first reading
if None in (prev, val):
return None, val
# counter increased, use the difference
if val >= prev:
return val - prev, val
# counter wrapped and we have maxValue (and optionally minValue)
# calculate delta based on maxValue + 1 + val - prev - minValue
if maxValue is not None:
return maxValue + 1 + val - prev - (minValue or 0), val
# counter wrapped and we have maxValue
# calculate delta based on val - minValue
if minValue is not None:
return val - minValue, val
# counter wrapped or reset and we don't have minValue/maxValue
# just use None
return None, val
def stacked(requestContext,seriesLists,stackName='__DEFAULT__'):
"""
Takes one metric or a wildcard seriesList and change them so they are
stacked. This is a way of stacking just a couple of metrics without having
to use the stacked area mode (that stacks everything). By means of this a mixed
stacked and non stacked graph can be made
It can also take an optional argument with a name of the stack, in case there is
more than one, e.g. for input and output metrics.
Example:
.. code-block:: none
&target=stacked(company.server.application01.ifconfig.TXPackets, 'tx')
"""
if 'totalStack' in requestContext:
totalStack = requestContext['totalStack'].get(stackName, [])
else:
requestContext['totalStack'] = {}
totalStack = []
results = []
for series in seriesLists:
newValues = []
for i in range(len(series)):
if len(totalStack) <= i: totalStack.append(0)
if series[i] is not None:
totalStack[i] += series[i]
newValues.append(totalStack[i])
else:
newValues.append(None)
# Work-around for the case when legend is set
if stackName=='__DEFAULT__':
series.tags['stacked'] = stackName
newName = "stacked(%s)" % series.name
else:
newName = series.name
newSeries = series.copy(name=newName, values=newValues)
newSeries.options['stacked'] = True
results.append(newSeries)
requestContext['totalStack'][stackName] = totalStack
return results
stacked.group = 'Graph'
stacked.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('stack', ParamTypes.string),
]
def areaBetween(requestContext, seriesList):
"""
Draws the vertical area in between the two series in seriesList. Useful for
visualizing a range such as the minimum and maximum latency for a service.
areaBetween expects **exactly one argument** that results in exactly two series
(see example below). The order of the lower and higher values series does not
matter. The visualization only works when used in conjunction with
``areaMode=stacked``.
Most likely use case is to provide a band within which another metric should
move. In such case applying an ``alpha()``, as in the second example, gives
best visual results.
Example:
.. code-block:: none
&target=areaBetween(service.latency.{min,max})&areaMode=stacked
&target=alpha(areaBetween(service.latency.{min,max}),0.3)&areaMode=stacked
If for instance, you need to build a seriesList, you should use the ``group``
function, like so:
.. code-block:: none
&target=areaBetween(group(minSeries(a.*.min),maxSeries(a.*.max)))
"""
assert len(seriesList) == 2, "areaBetween series argument must reference *exactly* 2 series"
lower = seriesList[0]
upper = seriesList[1]
lower.options['stacked'] = True
lower.options['invisible'] = True
upper.options['stacked'] = True
upper.tags['areaBetween'] = 1
lower.tags = upper.tags
lower.name = upper.name = "areaBetween(%s)" % upper.pathExpression
return seriesList
areaBetween.group = 'Graph'
areaBetween.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def aliasSub(requestContext, seriesList, search, replace):
r"""
Runs series names through a regex search/replace.
.. code-block:: none
&target=aliasSub(ip.*TCP*,"^.*TCP(\d+)","\1")
"""
try:
seriesList.name = re.sub(search, replace, seriesList.name)
except AttributeError:
for series in seriesList:
series.name = re.sub(search, replace, series.name)
return seriesList
aliasSub.group = 'Alias'
aliasSub.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('search', ParamTypes.string, required=True),
Param('replace', ParamTypes.string, required=True),
]
def aliasQuery(requestContext, seriesList, search, replace, newName):
r"""
Performs a query to alias the metrics in seriesList.
.. code-block:: none
&target=aliasQuery(channel.power.*,"channel\.power\.([0-9]+)","channel.frequency.\1", "Channel %d MHz")
The series in seriesList will be aliased by first translating the series names using
the search & replace parameters, then using the last value of the resulting series
to construct the alias using sprintf-style syntax.
"""
for series in seriesList:
newQuery = re.sub(search, replace, series.name)
newContext = requestContext.copy()
newContext['prefetch'] = {}
newSeriesList = evaluateTarget(newContext, newQuery)
if newSeriesList is None or len(newSeriesList) == 0:
raise InputParameterError('No series found with query: ' + newQuery)
current = safe.safeLast(newSeriesList[0])
if current is None:
raise InputParameterError('Cannot get last value of series: ' + newSeriesList[0])
series.name = newName % current
return seriesList
aliasQuery.group = 'Alias'
aliasQuery.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('search', ParamTypes.string, required=True),
Param('replace', ParamTypes.string, required=True),
Param('newName', ParamTypes.string, required=True),
]
def alias(requestContext, seriesList, newName):
"""
Takes one metric or a wildcard seriesList and a string in quotes.
Prints the string instead of the metric name in the legend.
.. code-block:: none
&target=alias(Sales.widgets.largeBlue,"Large Blue Widgets")
"""
try:
seriesList.name = newName
except AttributeError:
for series in seriesList:
series.name = newName
return seriesList
alias.group = 'Alias'
alias.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('newName', ParamTypes.string, required=True),
]
def cactiStyle(requestContext, seriesList, system=None, units=None):
"""
Takes a series list and modifies the aliases to provide column aligned
output with Current, Max, and Min values in the style of cacti. Optionally
takes a "system" value to apply unit formatting in the same style as the
Y-axis, or a "unit" string to append an arbitrary unit suffix.
.. code-block:: none
&target=cactiStyle(ganglia.*.net.bytes_out,"si")
&target=cactiStyle(ganglia.*.net.bytes_out,"si","b")
A possible value for ``system`` is ``si``, which would express your values in
multiples of a thousand. A second option is to use ``binary`` which will
instead express your values in multiples of 1024 (useful for network devices).
Column alignment of the Current, Max, Min values works under two conditions:
you use a monospace font such as terminus and use a single cactiStyle call, as
separate cactiStyle calls are not aware of each other. In case you have
different targets for which you would like to have cactiStyle to line up, you
can use ``group()`` to combine them before applying cactiStyle, such as:
.. code-block:: none
&target=cactiStyle(group(metricA,metricB))
"""
if 0 == len(seriesList):
return seriesList
if system:
if units:
fmt = lambda x:"%.2f %s" % format_units(x,system=system,units=units)
else:
fmt = lambda x:"%.2f%s" % format_units(x,system=system)
else:
if units:
fmt = lambda x: "%.2f %s" % (x, units)
else:
fmt = lambda x: "%.2f" % x
nameLen = max([0] + [len(getattr(series,"name")) for series in seriesList])
lastLen = max([0] + [len(fmt(int(safe.safeLast(series) or 3))) for series in seriesList]) + 3
maxLen = max([0] + [len(fmt(int(safe.safeMax(series) or 3))) for series in seriesList]) + 3
minLen = max([0] + [len(fmt(int(safe.safeMin(series) or 3))) for series in seriesList]) + 3
for series in seriesList:
last = safe.safeLast(series)
maximum = safe.safeMax(series)
minimum = safe.safeMin(series)
if last is None:
last = NAN
else:
last = fmt(float(last))
if maximum is None:
maximum = NAN
else:
maximum = fmt(float(maximum))
if minimum is None:
minimum = NAN
else:
minimum = fmt(float(minimum))
series.name = "%*s Current:%*s Max:%*s Min:%*s " % \
(-nameLen, series.name,
-lastLen, last,
-maxLen, maximum,
-minLen, minimum)
return seriesList
cactiStyle.group = 'Special'
cactiStyle.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('system', ParamTypes.string, options=['si', 'binary']),
Param('units', ParamTypes.string),
]
def _getFirstPathExpression(name):
"""Returns the first metric path in an expression."""
tokens = grammar.parseString(name)
pathExpression = None
while pathExpression is None:
if tokens.pathExpression:
pathExpression = tokens.pathExpression
elif tokens.expression:
tokens = tokens.expression
elif tokens.call:
tokens = tokens.call.args[0]
else:
break
return pathExpression
def aliasByNode(requestContext, seriesList, *nodes):
"""
Takes a seriesList and applies an alias derived from one or more "node"
portion/s of the target name or tags. Node indices are 0 indexed.
.. code-block:: none
&target=aliasByNode(ganglia.*.cpu.load5,1)
Each node may be an integer referencing a node in the series name or a string identifying a tag.
.. code-block:: none
&target=seriesByTag("name=~cpu.load.*", "server=~server[1-9]+", "datacenter=dc1")|aliasByNode("datacenter", "server", 1)
# will produce output series like
# dc1.server1.load5, dc1.server2.load5, dc1.server1.load10, dc1.server2.load10
"""
for series in seriesList:
series.name = aggKey(series, nodes)
return seriesList
aliasByNode.group = 'Alias'
aliasByNode.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('nodes', ParamTypes.nodeOrTag, required=True, multiple=True),
]
def aliasByMetric(requestContext, seriesList):
"""
Takes a seriesList and applies an alias derived from the base metric name.
.. code-block:: none
&target=aliasByMetric(carbon.agents.graphite.creates)
"""
return substr(requestContext, seriesList, -1, 0)
aliasByMetric.group = 'Alias'
aliasByMetric.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def legendValue(requestContext, seriesList, *valueTypes):
"""
Takes one metric or a wildcard seriesList and a string in quotes.
Appends a value to the metric name in the legend. Currently one or several of: `last`, `avg`,
`total`, `min`, `max`.
The last argument can be `si` (default) or `binary`, in that case values will be formatted in the
corresponding system.
.. code-block:: none
&target=legendValue(Sales.widgets.largeBlue, 'avg', 'max', 'si')
"""
system = None
if valueTypes[-1] in ('si', 'binary'):
system = valueTypes[-1]
valueTypes = valueTypes[:-1]
for valueType in valueTypes:
try:
valueFunc = getAggFunc(valueType)
except InputParameterError:
valueFunc = lambda s: '(?)'
if system is None:
for series in seriesList:
series.name += " (%s: %s)" % (valueType, valueFunc(series))
else:
for series in seriesList:
value = valueFunc(series)
formatted = None
if isinstance(value, six.string_types):
formatted = value
elif value is not None:
formatted = "%.2f%s" % format_units(value, system=system)
series.name = "%-20s%-5s%-10s" % (series.name, valueType, formatted)
return seriesList
legendValue.group = 'Alias'
legendValue.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('valuesTypes', ParamTypes.string, multiple=True, options=ParamTypeAggFunc.getAllValidAggFuncs() + ['si', 'binary']),
]
def toUpperCase(requestContext, seriesList, *pos):
"""
Takes one metric or a wildcard seriesList and uppers the case of each letter.
Optionally, a letter position to upper case can be specified, in which case
only the letter at the specified position gets upper-cased.
The position parameter may be given multiple times.
The position parameter may be negative to define a position relative to the
end of the metric name.
"""
for series in seriesList:
if len(pos) == 0:
series.name = series.name.upper()
else:
tmpName = list(series.name)
for i in pos:
assert isinstance(i, int)
try:
tmpName[i] = tmpName[i].upper()
except IndexError:
pass
series.name = "".join(tmpName)
return seriesList
toUpperCase.group = 'Alias'
toUpperCase.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('pos', ParamTypes.integer, multiple=True)
]
def toLowerCase(requestContext, seriesList, *pos):
"""
Takes one metric or a wildcard seriesList and lowers the case of each letter.
Optionally, a letter position to lower case can be specified, in which case
only the letter at the specified position gets lower-cased.
The position parameter may be given multiple times.
The position parameter may be negative to define a position relative to the
end of the metric name.
"""
for series in seriesList:
if len(pos) == 0:
series.name = series.name.lower()
else:
tmpName = list(series.name)
for i in pos:
assert isinstance(i, int)
try:
tmpName[i] = tmpName[i].lower()
except IndexError:
pass
series.name = "".join(tmpName)
return seriesList
toLowerCase.group = 'Alias'
toLowerCase.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('pos', ParamTypes.integer, multiple=True)
]
def alpha(requestContext, seriesList, alpha):
"""
Assigns the given alpha transparency setting to the series. Takes a float value between 0 and 1.
"""
for series in seriesList:
series.options['alpha'] = alpha
return seriesList
alpha.group = 'Graph'
alpha.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('alpha', ParamTypes.float, required=True),
]
def color(requestContext, seriesList, theColor):
"""
Assigns the given color to the seriesList
Example:
.. code-block:: none
&target=color(collectd.hostname.cpu.0.user, 'green')
&target=color(collectd.hostname.cpu.0.system, 'ff0000')
&target=color(collectd.hostname.cpu.0.idle, 'gray')
&target=color(collectd.hostname.cpu.0.idle, '6464ffaa')
"""
for series in seriesList:
series.color = theColor
return seriesList
color.group = 'Graph'
color.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('theColor', ParamTypes.string, required=True),
]
def substr(requestContext, seriesList, start=0, stop=0):
"""
Takes one metric or a wildcard seriesList followed by 1 or 2 integers. Assume that the
metric name is a list or array, with each element separated by dots. Prints
n - length elements of the array (if only one integer n is passed) or n - m
elements of the array (if two integers n and m are passed). The list starts
with element 0 and ends with element (length - 1).
Example:
.. code-block:: none
&target=substr(carbon.agents.hostname.avgUpdateTime,2,4)
The label would be printed as "hostname.avgUpdateTime".
"""
for series in seriesList:
left = series.name.rfind('(') + 1
right = series.name.find(')')
if right < 0:
right = len(series.name)+1
cleanName = series.name[left:right:]
if int(stop) == 0:
series.name = '.'.join(cleanName.split('.')[int(start)::])
else:
series.name = '.'.join(cleanName.split('.')[int(start):int(stop):])
# substr(func(a.b,'c'),1) becomes b instead of b,'c'
series.name = re.sub(',.*$', '', series.name)
return seriesList
substr.group = 'Special'
substr.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('start', ParamTypes.node, default=0),
Param('stop', ParamTypes.node, default=0),
]
def logarithm(requestContext, seriesList, base=10):
"""
Takes one metric or a wildcard seriesList, a base, and draws the y-axis in logarithmic
format. If base is omitted, the function defaults to base 10.
Example:
.. code-block:: none
&target=log(carbon.agents.hostname.avgUpdateTime,2)
"""
results = []
for series in seriesList:
newValues = []
for val in series:
if val is None:
newValues.append(None)
elif val <= 0:
newValues.append(None)
else:
newValues.append(math.log(val, base))
series.tags['log'] = base
newName = "log(%s, %s)" % (series.name, base)
newSeries = series.copy(name=newName, values=newValues)
results.append(newSeries)
return results
logarithm.group = 'Transform'
logarithm.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('base', ParamTypes.integer, default=10),
]
operatorFuncs = {
'=': (lambda val, threshold: val is not None and val == threshold),
'!=': (lambda val, threshold: val is None or val != threshold),
'>': (lambda val, threshold: val is not None and val > threshold),
'>=': (lambda val, threshold: val is not None and val >= threshold),
'<': (lambda val, threshold: val is None or val < threshold),
'<=': (lambda val, threshold: val is None or val <= threshold),
}
def filterSeries(requestContext, seriesList, func, operator, threshold):
"""
Takes one metric or a wildcard seriesList followed by a consolidation function, an operator and a threshold.
Draws only the metrics which match the filter expression.
Example:
.. code-block:: none
&target=filterSeries(system.interface.eth*.packetsSent, 'max', '>', 1000)
This would only display interfaces which has a peak throughput higher than 1000 packets/min.
Supported aggregation functions: ``average``, ``median``, ``sum``, ``min``,
``max``, ``diff``, ``stddev``, ``range``, ``multiply`` & ``last``.
Supported operators: ``=``, ``!=``, ``>``, ``>=``, ``<`` & ``<=``.
"""
consolidationFunc = getAggFunc(func)
if operator not in operatorFuncs:
raise InputParameterError('Unsupported operator: %s' % (operator))
operatorFunc = operatorFuncs[operator]
# if seriesList is empty then just short-circuit
if not seriesList:
return []
return [series for series in seriesList if operatorFunc(consolidationFunc(series), threshold)]
filterSeries.group = 'Filter Series'
filterSeries.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('func', ParamTypes.aggFunc, required=True),
Param('operator', ParamTypes.string, required=True, options=sorted(operatorFuncs.keys())),
Param('threshold', ParamTypes.float, required=True),
]
def maximumAbove(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by a constant n.
Draws only the metrics with a maximum value above n.
Example:
.. code-block:: none
&target=maximumAbove(system.interface.eth*.packetsSent,1000)
This would only display interfaces which sent more than 1000 packets/min.
"""
return filterSeries(requestContext, seriesList, 'max', '>', n)
maximumAbove.group = 'Filter Series'
maximumAbove.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.float, required=True),
]
def minimumAbove(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by a constant n.
Draws only the metrics with a minimum value above n.
Example:
.. code-block:: none
&target=minimumAbove(system.interface.eth*.packetsSent,1000)
This would only display interfaces which sent more than 1000 packets/min.
"""
return filterSeries(requestContext, seriesList, 'min', '>', n)
minimumAbove.group = 'Filter Series'
minimumAbove.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.float, required=True),
]
def maximumBelow(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by a constant n.
Draws only the metrics with a maximum value below n.
Example:
.. code-block:: none
&target=maximumBelow(system.interface.eth*.packetsSent,1000)
This would only display interfaces which sent less than 1000 packets/min.
"""
return filterSeries(requestContext, seriesList, 'max', '<=', n)
maximumBelow.group = 'Filter Series'
maximumBelow.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.float, required=True),
]
def minimumBelow(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by a constant n.
Draws only the metrics with a minimum value below or equal to n.
Example:
.. code-block:: none
&target=minimumBelow(system.interface.eth*.packetsSent,1000)
This would only display interfaces which at one point sent less than 1000 packets/min.
"""
return filterSeries(requestContext, seriesList, 'min', '<=', n)
minimumBelow.group = 'Filter Series'
minimumBelow.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.float, required=True),
]
def highest(requestContext, seriesList, n=1, func='average'):
"""
Takes one metric or a wildcard seriesList followed by an integer N and an aggregation function.
Out of all metrics passed, draws only the N metrics with the highest aggregated value over the
time period specified.
Example:
.. code-block:: none
&target=highest(server*.instance*.threads.busy,5,'max')
Draws the 5 servers with the highest number of busy threads.
"""
seriesList.sort(key=keyFunc(getAggFunc(func)), reverse=True)
return seriesList[:int(n)]
highest.group = 'Filter Series'
highest.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.integer, required=True),
Param('func', ParamTypes.aggFunc, default='average'),
]
def lowest(requestContext, seriesList, n=1, func='average'):
"""
Takes one metric or a wildcard seriesList followed by an integer N and an aggregation function.
Out of all metrics passed, draws only the N metrics with the lowest aggregated value over the
time period specified.
Example:
.. code-block:: none
&target=lowest(server*.instance*.threads.busy,5,'min')
Draws the 5 servers with the lowest number of busy threads.
"""
seriesList.sort(key=keyFunc(getAggFunc(func)))
return seriesList[:int(n)]
lowest.group = 'Filter Series'
lowest.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.integer, required=True),
Param('func', ParamTypes.aggFunc, default='average'),
]
def highestCurrent(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Out of all metrics passed, draws only the N metrics with the highest value
at the end of the time period specified.
Example:
.. code-block:: none
&target=highestCurrent(server*.instance*.threads.busy,5)
Draws the 5 servers with the highest busy threads.
This is an alias for :py:func:`highest <highest>` with aggregation ``current``.
"""
return highest(requestContext, seriesList, n, 'current')
highestCurrent.group = 'Filter Series'
highestCurrent.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.integer, required=True),
]
def highestMax(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Out of all metrics passed, draws only the N metrics with the highest maximum
value in the time period specified.
Example:
.. code-block:: none
&target=highestMax(server*.instance*.threads.busy,5)
Draws the top 5 servers who have had the most busy threads during the time
period specified.
This is an alias for :py:func:`highest <highest>` with aggregation ``max``.
"""
return highest(requestContext, seriesList, n, 'max')
highestMax.group = 'Filter Series'
highestMax.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.integer, required=True),
]
def lowestCurrent(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Out of all metrics passed, draws only the N metrics with the lowest value at
the end of the time period specified.
Example:
.. code-block:: none
&target=lowestCurrent(server*.instance*.threads.busy,5)
Draws the 5 servers with the least busy threads right now.
This is an alias for :py:func:`lowest <lowest>` with aggregation ``current``.
"""
return lowest(requestContext, seriesList, n, 'current')
lowestCurrent.group = 'Filter Series'
lowestCurrent.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.integer, required=True),
]
def currentAbove(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by a constant N.
Out of all metrics passed, draws only the metrics whose value is above N
at the end of the time period specified.
Example:
.. code-block:: none
&target=currentAbove(server*.instance*.threads.busy,50)
Draws the servers with more than 50 busy threads.
"""
return filterSeries(requestContext, seriesList, 'last', '>', n)
currentAbove.group = 'Filter Series'
currentAbove.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.float, required=True),
]
def currentBelow(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by a constant N.
Out of all metrics passed, draws only the metrics whose value is below N
at the end of the time period specified.
Example:
.. code-block:: none
&target=currentBelow(server*.instance*.threads.busy,3)
Draws the servers with less than 3 busy threads.
"""
return filterSeries(requestContext, seriesList, 'last', '<=', n)
currentBelow.group = 'Filter Series'
currentBelow.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.float, required=True),
]
def highestAverage(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Out of all metrics passed, draws only the top N metrics with the highest
average value for the time period specified.
Example:
.. code-block:: none
&target=highestAverage(server*.instance*.threads.busy,5)
Draws the top 5 servers with the highest average value.
This is an alias for :py:func:`highest <highest>` with aggregation ``average``.
"""
return highest(requestContext, seriesList, n, 'average')
highestAverage.group = 'Filter Series'
highestAverage.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.integer, required=True),
]
def lowestAverage(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Out of all metrics passed, draws only the bottom N metrics with the lowest
average value for the time period specified.
Example:
.. code-block:: none
&target=lowestAverage(server*.instance*.threads.busy,5)
Draws the bottom 5 servers with the lowest average value.
This is an alias for :py:func:`lowest <lowest>` with aggregation ``average``.
"""
return lowest(requestContext, seriesList, n, 'average')
lowestAverage.group = 'Filter Series'
lowestAverage.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.integer, required=True),
]
def averageAbove(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by a constant N.
Out of all metrics passed, draws only the metrics with an average value
above N for the time period specified.
Example:
.. code-block:: none
&target=averageAbove(server*.instance*.threads.busy,25)
Draws the servers with average values above 25.
"""
return filterSeries(requestContext, seriesList, 'average', '>', n)
averageAbove.group = 'Filter Series'
averageAbove.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.float, required=True),
]
def averageBelow(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by a constant N.
Out of all metrics passed, draws only the metrics with an average value
below N for the time period specified.
Example:
.. code-block:: none
&target=averageBelow(server*.instance*.threads.busy,25)
Draws the servers with average values below 25.
"""
return filterSeries(requestContext, seriesList, 'average', '<=', n)
averageBelow.group = 'Filter Series'
averageBelow.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.float, required=True),
]
def _getPercentile(points, n, interpolate=False):
"""
Percentile is calculated using the method outlined in the NIST Engineering
Statistics Handbook:
http://www.itl.nist.gov/div898/handbook/prc/section2/prc252.htm
"""
sortedPoints = sorted([ p for p in points if p is not None])
if len(sortedPoints) == 0:
return None
fractionalRank = (n/100.0) * (len(sortedPoints) + 1)
rank = int(fractionalRank)
rankFraction = fractionalRank - rank
if not interpolate:
rank += int(math.ceil(rankFraction))
if rank == 0:
percentile = sortedPoints[0]
elif rank - 1 == len(sortedPoints):
percentile = sortedPoints[-1]
else:
percentile = sortedPoints[rank - 1] # Adjust for 0-index
if interpolate:
if rank != len(sortedPoints): # if a next value exists
nextValue = sortedPoints[rank]
percentile = percentile + rankFraction * (nextValue - percentile)
return percentile
def nPercentile(requestContext, seriesList, n):
"""Returns n-percent of each series in the seriesList."""
assert n, 'The requested percent is required to be greater than 0'
results = []
for s in seriesList:
# Create a sorted copy of the TimeSeries excluding None values in the values list.
s_copy = s.copy(values=sorted( [item for item in s if item is not None] ))
if not s_copy:
continue # Skip this series because it is empty.
perc_val = _getPercentile(s_copy, n)
if perc_val is not None:
s_copy.tags['nPercentile'] = n
name = 'nPercentile(%s, %g)' % (s_copy.name, n)
point_count = int((s.end - s.start)/s.step)
perc_series = s_copy.copy(name=name, values=[perc_val] * point_count)
results.append(perc_series)
return results
nPercentile.group = 'Calculate'
nPercentile.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.float, required=True),
]
def averageOutsidePercentile(requestContext, seriesList, n):
"""
Removes series lying inside an average percentile interval
"""
averages = [safe.safeAvg(s) for s in seriesList]
if n < 50:
n = 100 - n
lowPercentile = _getPercentile(averages, 100 - n)
highPercentile = _getPercentile(averages, n)
return [s for s in seriesList if not lowPercentile < safe.safeAvg(s) < highPercentile]
averageOutsidePercentile.group = 'Filter Series'
averageOutsidePercentile.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.float, required=True),
]
def removeBetweenPercentile(requestContext, seriesList, n):
"""
Removes series that do not have an value lying in the x-percentile of all the values at a moment
"""
if n < 50:
n = 100 - n
transposed = list(zip(*seriesList))
lowPercentiles = [_getPercentile(col, 100-n) for col in transposed]
highPercentiles = [_getPercentile(col, n) for col in transposed]
return [l for l in seriesList if sum([not lowPercentiles[val_i] < val < highPercentiles[val_i]
for (val_i, val) in enumerate(l)]) > 0]
removeBetweenPercentile.group = 'Filter Series'
removeBetweenPercentile.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.float, required=True),
]
def removeAbovePercentile(requestContext, seriesList, n):
"""
Removes data above the nth percentile from the series or list of series provided.
Values above this percentile are assigned a value of None.
"""
for s in seriesList:
s.name = 'removeAbovePercentile(%s, %g)' % (s.name, n)
s.pathExpression = s.name
try:
percentile = nPercentile(requestContext, [s], n)[0][0]
except IndexError:
continue
for (index, val) in enumerate(s):
if val is not None and val > percentile:
s[index] = None
return seriesList
removeAbovePercentile.group = 'Filter Data'
removeAbovePercentile.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.float, required=True),
]
def removeAboveValue(requestContext, seriesList, n):
"""
Removes data above the given threshold from the series or list of series provided.
Values above this threshold are assigned a value of None.
"""
for s in seriesList:
s.name = 'removeAboveValue(%s, %g)' % (s.name, n)
s.pathExpression = s.name
for (index, val) in enumerate(s):
if val is not None and val > n:
s[index] = None
return seriesList
removeAboveValue.group = 'Filter Data'
removeAboveValue.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.float, required=True),
]
def removeBelowPercentile(requestContext, seriesList, n):
"""
Removes data below the nth percentile from the series or list of series provided.
Values below this percentile are assigned a value of None.
"""
for s in seriesList:
s.name = 'removeBelowPercentile(%s, %g)' % (s.name, n)
s.pathExpression = s.name
try:
percentile = nPercentile(requestContext, [s], n)[0][0]
except IndexError:
continue
for (index, val) in enumerate(s):
if val is None or val < percentile:
s[index] = None
return seriesList
removeBelowPercentile.group = 'Filter Data'
removeBelowPercentile.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.float, required=True),
]
def removeBelowValue(requestContext, seriesList, n):
"""
Removes data below the given threshold from the series or list of series provided.
Values below this threshold are assigned a value of None.
"""
for s in seriesList:
s.name = 'removeBelowValue(%s, %g)' % (s.name, n)
s.pathExpression = s.name
for (index, val) in enumerate(s):
if val is None or val < n:
s[index] = None
return seriesList
removeBelowValue.group = 'Filter Data'
removeBelowValue.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.float, required=True),
]
def limit(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Only draw the first N metrics. Useful when testing a wildcard in a metric.
Example:
.. code-block:: none
&target=limit(server*.instance*.memory.free,5)
Draws only the first 5 instance's memory free.
"""
return seriesList[0:n]
limit.group = 'Filter Series'
limit.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.integer, required=True),
]
def sortBy(requestContext, seriesList, func='average', reverse=False):
"""
Takes one metric or a wildcard seriesList followed by an aggregation function and an
optional ``reverse`` parameter.
Returns the metrics sorted according to the specified function.
Example:
.. code-block:: none
&target=sortBy(server*.instance*.threads.busy,'max')
Draws the servers in ascending order by maximum.
"""
seriesList.sort(key=keyFunc(getAggFunc(func)), reverse=reverse)
return seriesList
sortBy.group = 'Sorting'
sortBy.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('func', ParamTypes.aggFunc, default='average'),
Param('reverse', ParamTypes.boolean, default=False),
]
def sortByName(requestContext, seriesList, natural=False, reverse=False):
"""
Takes one metric or a wildcard seriesList.
Sorts the list of metrics by the metric name using either alphabetical order or natural sorting.
Natural sorting allows names containing numbers to be sorted more naturally, e.g:
- Alphabetical sorting: server1, server11, server12, server2
- Natural sorting: server1, server2, server11, server12
"""
def natSortKey(series):
return re.sub(r"(\d+)", lambda x: "{0:010}".format(int(x.group(0))), series.name)
if natural:
seriesList.sort(key=natSortKey, reverse=reverse)
else:
seriesList.sort(key=lambda x: x.name, reverse=reverse)
return seriesList
sortByName.group = 'Sorting'
sortByName.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('natural', ParamTypes.boolean, default=False),
Param('reverse', ParamTypes.boolean, default=False),
]
def sortByTotal(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
Sorts the list of metrics in descending order by the sum of values across the time period
specified.
"""
return sortBy(requestContext, seriesList, 'sum', reverse=True)
sortByTotal.group = 'Sorting'
sortByTotal.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def sortByMaxima(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
Sorts the list of metrics in descending order by the maximum value across the time period
specified. Useful with the &areaMode=all parameter, to keep the
lowest value lines visible.
Example:
.. code-block:: none
&target=sortByMaxima(server*.instance*.memory.free)
"""
seriesList.sort(key=keyFunc(safe.safeMax), reverse=True)
return seriesList
sortByMaxima.group = 'Sorting'
sortByMaxima.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def sortByMinima(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
Sorts the list of metrics by the lowest value across the time period
specified, including only series that have a maximum value greater than 0.
Example:
.. code-block:: none
&target=sortByMinima(server*.instance*.memory.free)
"""
newSeries = [series for series in seriesList if safe.safeMax(series, default=0) > 0]
newSeries.sort(key=keyFunc(safe.safeMin))
return newSeries
sortByMinima.group = 'Sorting'
sortByMinima.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def useSeriesAbove(requestContext, seriesList, value, search, replace):
"""
Compares the maximum of each series against the given `value`. If the series
maximum is greater than `value`, the regular expression search and replace is
applied against the series name to plot a related metric
e.g. given useSeriesAbove(ganglia.metric1.reqs,10,'reqs','time'),
the response time metric will be plotted only when the maximum value of the
corresponding request/s metric is > 10
.. code-block:: none
&target=useSeriesAbove(ganglia.metric1.reqs,10,"reqs","time")
"""
newNames = []
for series in seriesList:
newname = re.sub(search, replace, series.name)
if max(series) > value:
newNames.append(newname)
if not newNames:
return []
newContext = requestContext.copy()
newContext['prefetched'] = {}
newSeries = evaluateTarget(newContext, 'group(%s)' % ','.join(newNames))
return [n for n in newSeries if n is not None and len(n) > 0]
useSeriesAbove.group = 'Filter Series'
useSeriesAbove.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('value', ParamTypes.float, required=True),
Param('search', ParamTypes.string, required=True),
Param('replace', ParamTypes.string, required=True),
]
def fallbackSeries(requestContext, seriesList, fallback):
"""
Takes a wildcard seriesList, and a second fallback metric.
If the wildcard does not match any series, draws the fallback metric.
Example:
.. code-block:: none
&target=fallbackSeries(server*.requests_per_second, constantLine(0))
Draws a 0 line when server metric does not exist.
"""
if len(seriesList) > 0:
return seriesList
else:
return fallback
fallbackSeries.group = 'Special'
fallbackSeries.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('fallback', ParamTypes.seriesList, required=True),
]
def mostDeviant(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Draws the N most deviant metrics.
To find the deviants, the standard deviation (sigma) of each series
is taken and ranked. The top N standard deviations are returned.
Example:
.. code-block:: none
&target=mostDeviant(server*.instance*.memory.free, 5)
Draws the 5 instances furthest from the average memory free.
"""
deviants = []
for series in seriesList:
mean = safe.safeAvg(series)
if mean is None: continue
square_sum = sum([ (value - mean) ** 2 for value in series if value is not None ])
sigma = safe.safeDiv(square_sum, safe.safeLen(series))
if sigma is None: continue
deviants.append( (sigma, series) )
deviants.sort(key=keyFunc(lambda i: i[0]), reverse=True) #sort by sigma
return [ series for (_, series) in deviants ][:n] #return the n most deviant series
mostDeviant.group = 'Filter Series'
mostDeviant.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('n', ParamTypes.integer, required=True),
]
def stdev(requestContext, seriesList, points, windowTolerance=0.1):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Draw the Standard Deviation of all metrics passed for the past N datapoints.
If the ratio of null points in the window is greater than windowTolerance,
skip the calculation. The default for windowTolerance is 0.1 (up to 10% of points
in the window can be missing). Note that if this is set to 0.0, it will cause large
gaps in the output anywhere a single point is missing.
Example:
.. code-block:: none
&target=stdev(server*.instance*.threads.busy,30)
&target=stdev(server*.instance*.cpu.system,30,0.0)
"""
# For this we take the standard deviation in terms of the moving average
# and the moving average of series squares.
for (seriesIndex,series) in enumerate(seriesList):
series.tags['stdev'] = points
name = "stdev(%s,%d)" % (series.name, int(points))
stdevSeries = series.copy(name=name, values=[])
validPoints = 0
currentSum = 0
currentSumOfSquares = 0
for (index, newValue) in enumerate(series):
# Mark whether we've reached our window size - dont drop points out otherwise
if index < points:
bootstrapping = True
droppedValue = None
else:
bootstrapping = False
droppedValue = series[index - points]
# Track non-None points in window
if not bootstrapping and droppedValue is not None:
validPoints -= 1
if newValue is not None:
validPoints += 1
# Remove the value that just dropped out of the window
if not bootstrapping and droppedValue is not None:
currentSum -= droppedValue
currentSumOfSquares -= droppedValue**2
# Add in the value that just popped in the window
if newValue is not None:
currentSum += newValue
currentSumOfSquares += newValue**2
if validPoints > 0 and float(validPoints)/points >= windowTolerance:
try:
deviation = math.sqrt(validPoints * currentSumOfSquares - currentSum**2)/validPoints
except ValueError:
deviation = None
stdevSeries.append(deviation)
else:
stdevSeries.append(None)
seriesList[seriesIndex] = stdevSeries
return seriesList
stdev.group = 'Calculate'
stdev.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('points', ParamTypes.integer, required=True),
Param('windowTolerance', ParamTypes.float, default=0.1),
]
def secondYAxis(requestContext, seriesList):
"""
Graph the series on the secondary Y axis.
"""
for series in seriesList:
series.options['secondYAxis'] = True
series.tags['secondYAxis'] = 1
series.name= 'secondYAxis(%s)' % series.name
return seriesList
secondYAxis.group = 'Graph'
secondYAxis.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def holtWintersIntercept(alpha,actual,last_season,last_intercept,last_slope):
return alpha * (actual - last_season) \
+ (1 - alpha) * (last_intercept + last_slope)
def holtWintersSlope(beta,intercept,last_intercept,last_slope):
return beta * (intercept - last_intercept) + (1 - beta) * last_slope
def holtWintersSeasonal(gamma,actual,intercept,last_season):
return gamma * (actual - intercept) + (1 - gamma) * last_season
def holtWintersDeviation(gamma,actual,prediction,last_seasonal_dev):
if prediction is None:
prediction = 0
return gamma * math.fabs(actual - prediction) + (1 - gamma) * last_seasonal_dev
def holtWintersAnalysis(series, seasonality='1d'):
alpha = gamma = 0.1
beta = 0.0035
# season is currently one day
seasonality_time = parseTimeOffset(seasonality)
season_length = (seasonality_time.seconds + (seasonality_time.days * 86400)) // series.step
intercept = 0
slope = 0
intercepts = list()
slopes = list()
seasonals = list()
predictions = list()
deviations = list()
def getLastSeasonal(i):
j = i - season_length
if j >= 0:
return seasonals[j]
return 0
def getLastDeviation(i):
j = i - season_length
if j >= 0:
return deviations[j]
return 0
last_seasonal = 0
last_seasonal_dev = 0
next_last_seasonal = 0
next_pred = None
for i,actual in enumerate(series):
if actual is None:
# missing input values break all the math
# do the best we can and move on
intercepts.append(None)
slopes.append(0)
seasonals.append(0)
predictions.append(next_pred)
deviations.append(0)
next_pred = None
continue
if i == 0:
last_intercept = actual
last_slope = 0
# seed the first prediction as the first actual
prediction = actual
else:
last_intercept = intercepts[-1]
last_slope = slopes[-1]
if last_intercept is None:
last_intercept = actual
prediction = next_pred
last_seasonal = getLastSeasonal(i)
next_last_seasonal = getLastSeasonal(i+1)
last_seasonal_dev = getLastDeviation(i)
intercept = holtWintersIntercept(alpha,actual,last_seasonal
,last_intercept,last_slope)
slope = holtWintersSlope(beta,intercept,last_intercept,last_slope)
seasonal = holtWintersSeasonal(gamma,actual,intercept,last_seasonal)
next_pred = intercept + slope + next_last_seasonal
deviation = holtWintersDeviation(gamma,actual,prediction,last_seasonal_dev)
intercepts.append(intercept)
slopes.append(slope)
seasonals.append(seasonal)
predictions.append(prediction)
deviations.append(deviation)
# make the new forecast series
forecastTags = series.tags
forecastTags['holtWintersForecast'] = 1
forecastName = "holtWintersForecast(%s)" % series.name
forecastSeries = TimeSeries(forecastName, series.start, series.end
, series.step, predictions, tags=forecastTags, xFilesFactor=series.xFilesFactor)
# make the new deviation series
deviationTags = series.tags
deviationTags['holtWintersDeviation'] = 1
deviationName = "holtWintersDeviation(%s)" % series.name
deviationSeries = TimeSeries(deviationName, series.start, series.end
, series.step, deviations, tags=deviationTags, xFilesFactor=series.xFilesFactor)
results = {
'predictions': forecastSeries,
'deviations' : deviationSeries,
'intercepts' : intercepts,
'slopes' : slopes,
'seasonals' : seasonals,
}
return results
def holtWintersForecast(requestContext, seriesList, bootstrapInterval='7d', seasonality='1d'):
"""
Performs a Holt-Winters forecast using the series as input data. Data from
`bootstrapInterval` (one week by default) previous to the series is used to bootstrap the initial forecast.
"""
bootstrap = parseTimeOffset(bootstrapInterval)
previewSeconds = bootstrap.seconds + (bootstrap.days * 86400)
# ignore original data and pull new, including our preview
newContext = requestContext.copy()
newContext['prefetch'] = {}
newContext['startTime'] = requestContext['startTime'] - timedelta(seconds=previewSeconds)
previewList = evaluateTarget(newContext, requestContext['args'][0])
results = []
for series in previewList:
analysis = holtWintersAnalysis(series, seasonality)
predictions = analysis['predictions']
windowPoints = previewSeconds // predictions.step
series.tags['holtWintersForecast'] = 1
forecastName = "holtWintersForecast(%s)" % series.name
result = TimeSeries(forecastName, predictions.start + previewSeconds, predictions.end,
predictions.step, predictions[windowPoints:], tags=series.tags,
xFilesFactor=series.xFilesFactor)
results.append(result)
return results
holtWintersForecast.group = 'Calculate'
holtWintersForecast.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('bootstrapInterval', ParamTypes.interval, default='7d', suggestions=['7d', '30d']),
Param('seasonality', ParamTypes.interval, default='1d', suggestions=['1d', '7d']),
]
def holtWintersConfidenceBands(requestContext, seriesList, delta=3, bootstrapInterval='7d', seasonality='1d'):
"""
Performs a Holt-Winters forecast using the series as input data and plots
upper and lower bands with the predicted forecast deviations.
"""
bootstrap = parseTimeOffset(bootstrapInterval)
previewSeconds = bootstrap.seconds + (bootstrap.days * 86400)
# ignore original data and pull new, including our preview
newContext = requestContext.copy()
newContext['prefetch'] = {}
newContext['startTime'] = requestContext['startTime'] - timedelta(seconds=previewSeconds)
previewList = evaluateTarget(newContext, requestContext['args'][0])
results = []
for series in previewList:
analysis = holtWintersAnalysis(series, seasonality)
data = analysis['predictions']
windowPoints = previewSeconds // data.step
forecast = TimeSeries(data.name, data.start + previewSeconds, data.end, data.step, data[windowPoints:], xFilesFactor=series.xFilesFactor)
forecast.pathExpression = data.pathExpression
data = analysis['deviations']
windowPoints = previewSeconds // data.step
deviation = TimeSeries(data.name, data.start + previewSeconds, data.end, data.step, data[windowPoints:], xFilesFactor=series.xFilesFactor)
deviation.pathExpression = data.pathExpression
seriesLength = len(forecast)
i = 0
upperBand = list()
lowerBand = list()
while i < seriesLength:
forecast_item = forecast[i]
deviation_item = deviation[i]
i = i + 1
if forecast_item is None or deviation_item is None:
upperBand.append(None)
lowerBand.append(None)
else:
scaled_deviation = delta * deviation_item
upperBand.append(forecast_item + scaled_deviation)
lowerBand.append(forecast_item - scaled_deviation)
upperTags = series.tags
upperTags['holtWintersConfidenceUpper'] = 1
upperName = "holtWintersConfidenceUpper(%s)" % series.name
lowerTags = series.tags
lowerTags['holtWintersConfidenceLower'] = 1
lowerName = "holtWintersConfidenceLower(%s)" % series.name
upperSeries = TimeSeries(upperName, forecast.start, forecast.end
, forecast.step, upperBand, tags=upperTags, xFilesFactor=series.xFilesFactor)
lowerSeries = TimeSeries(lowerName, forecast.start, forecast.end
, forecast.step, lowerBand, tags=lowerTags, xFilesFactor=series.xFilesFactor)
upperSeries.pathExpression = series.pathExpression
lowerSeries.pathExpression = series.pathExpression
results.append(lowerSeries)
results.append(upperSeries)
return results
holtWintersConfidenceBands.group = 'Calculate'
holtWintersConfidenceBands.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('delta', ParamTypes.integer, default=3),
Param('bootstrapInterval', ParamTypes.interval, default='7d', suggestions=['7d', '30d']),
Param('seasonality', ParamTypes.interval, default='1d', suggestions=['1d', '7d']),
]
def holtWintersAberration(requestContext, seriesList, delta=3, bootstrapInterval='7d', seasonality='1d'):
"""
Performs a Holt-Winters forecast using the series as input data and plots the
positive or negative deviation of the series data from the forecast.
"""
results = []
confidenceBands = holtWintersConfidenceBands(requestContext, seriesList, delta, bootstrapInterval, seasonality)
confidenceBands = {s.name: s for s in confidenceBands}
for series in seriesList:
lowerBand = confidenceBands['holtWintersConfidenceLower(%s)' % series.name]
upperBand = confidenceBands['holtWintersConfidenceUpper(%s)' % series.name]
aberration = list()
for i, actual in enumerate(series):
if series[i] is None:
aberration.append(0)
elif upperBand[i] is not None and series[i] > upperBand[i]:
aberration.append(series[i] - upperBand[i])
elif lowerBand[i] is not None and series[i] < lowerBand[i]:
aberration.append(series[i] - lowerBand[i])
else:
aberration.append(0)
series.tags['holtWintersAberration'] = 1
newName = "holtWintersAberration(%s)" % series.name
results.append(TimeSeries(newName, series.start, series.end
, series.step, aberration, tags=series.tags, xFilesFactor=series.xFilesFactor))
return results
holtWintersAberration.group = 'Calculate'
holtWintersAberration.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('delta', ParamTypes.integer, default=3),
Param('bootstrapInterval', ParamTypes.interval, default='7d', suggestions=['7d', '30d']),
Param('seasonality', ParamTypes.interval, default='1d', suggestions=['1d', '7d']),
]
def holtWintersConfidenceArea(requestContext, seriesList, delta=3, bootstrapInterval='7d', seasonality='1d'):
"""
Performs a Holt-Winters forecast using the series as input data and plots the
area between the upper and lower bands of the predicted forecast deviations.
"""
bands = holtWintersConfidenceBands(requestContext, seriesList, delta, bootstrapInterval, seasonality)
results = areaBetween(requestContext, bands)
for series in results:
if 'areaBetween' in series.tags:
del series.tags['areaBetween']
series.tags['holtWintersConfidenceArea'] = 1
series.name = series.name.replace('areaBetween', 'holtWintersConfidenceArea')
series.pathExpression = series.name
return results
holtWintersConfidenceArea.group = 'Calculate'
holtWintersConfidenceArea.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('delta', ParamTypes.integer, default=3),
Param('bootstrapInterval', ParamTypes.interval, default='7d', suggestions=['7d', '30d']),
Param('seasonality', ParamTypes.interval, default='1d', suggestions=['1d', '7d']),
]
def _linearRegressionAnalysis(series):
"""
Returns factor and offset of linear regression function by least squares method.
"""
n = safe.safeLen(series)
sumI = sum([i for i,v in enumerate(series) if v is not None])
sumV = sum([v for i,v in enumerate(series) if v is not None])
sumII = sum([i*i for i,v in enumerate(series) if v is not None])
sumIV = sum([i*v for i,v in enumerate(series) if v is not None])
denominator = float(n*sumII - sumI*sumI)
if denominator == 0:
return None
else:
factor = (n * sumIV - sumI * sumV) / denominator / series.step
offset = (sumII * sumV - sumIV * sumI) / denominator - factor * series.start
return factor, offset
def linearRegression(requestContext, seriesList, startSourceAt=None, endSourceAt=None):
"""
Graphs the linear regression function by least squares method.
Takes one metric or a wildcard seriesList, followed by a quoted string with the
time to start the line and another quoted string with the time to end the line.
The start and end times are inclusive (default range is from to until). See
``from / until`` in the :doc:`Render API <render_api>` for examples of time formats. Datapoints
in the range is used to regression.
Example:
.. code-block:: none
&target=linearRegression(Server.instance01.threads.busy, '-1d')
&target=linearRegression(Server.instance*.threads.busy, "00:00 20140101","11:59 20140630")
"""
results = []
sourceContext = requestContext.copy()
sourceContext['prefetch'] = {}
if startSourceAt is not None: sourceContext['startTime'] = parseATTime(startSourceAt)
if endSourceAt is not None: sourceContext['endTime'] = parseATTime(endSourceAt)
sourceList = evaluateTarget(sourceContext, requestContext['args'][0])
for source,series in zip(sourceList, seriesList):
series.tags['linearRegressions'] = '%s, %s' % (
int(time.mktime(sourceContext['startTime'].timetuple())),
int(time.mktime(sourceContext['endTime'].timetuple()))
)
newName = 'linearRegression(%s, %s, %s)' % (
series.name,
int(time.mktime(sourceContext['startTime'].timetuple())),
int(time.mktime(sourceContext['endTime'].timetuple()))
)
forecast = _linearRegressionAnalysis(source)
if forecast is None:
continue
factor, offset = forecast
values = [ offset + (series.start + i * series.step) * factor for i in range(len(series)) ]
newSeries = TimeSeries(newName, series.start, series.end, series.step, values, tags=series.tags, xFilesFactor=series.xFilesFactor)
newSeries.pathExpression = newSeries.name
results.append(newSeries)
return results
linearRegression.group = 'Calculate'
linearRegression.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('startSourceAt', ParamTypes.date),
Param('endSourceAt', ParamTypes.date),
]
def drawAsInfinite(requestContext, seriesList):
"""
Takes one metric or a wildcard seriesList.
If the value is zero, draw the line at 0. If the value is above zero, draw
the line at infinity. If the value is null or less than zero, do not draw
the line.
Useful for displaying on/off metrics, such as exit codes. (0 = success,
anything else = failure.)
Example:
.. code-block:: none
drawAsInfinite(Testing.script.exitCode)
"""
for series in seriesList:
series.options['drawAsInfinite'] = True
series.tags['drawAsInfinite'] = 1
series.name = 'drawAsInfinite(%s)' % series.name
return seriesList
drawAsInfinite.group = 'Graph'
drawAsInfinite.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def lineWidth(requestContext, seriesList, width):
"""
Takes one metric or a wildcard seriesList, followed by a float F.
Draw the selected metrics with a line width of F, overriding the default
value of 1, or the &lineWidth=X.X parameter.
Useful for highlighting a single metric out of many, or having multiple
line widths in one graph.
Example:
.. code-block:: none
&target=lineWidth(server01.instance01.memory.free,5)
"""
for series in seriesList:
series.options['lineWidth'] = width
return seriesList
lineWidth.group = 'Graph'
lineWidth.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('width', ParamTypes.float, required=True),
]
def dashed(requestContext, seriesList, dashLength=5):
"""
Takes one metric or a wildcard seriesList, followed by a float F.
Draw the selected metrics with a dotted line with segments of length F
If omitted, the default length of the segments is 5.0
Example:
.. code-block:: none
&target=dashed(server01.instance01.memory.free,2.5)
"""
for series in seriesList:
series.tags['dashed'] = dashLength
series.name = 'dashed(%s, %g)' % (series.name, dashLength)
series.options['dashed'] = dashLength
return seriesList
dashed.group = 'Graph'
dashed.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('dashLength', ParamTypes.integer, default=5),
]
def timeStack(requestContext, seriesList, timeShiftUnit='1d', timeShiftStart=0, timeShiftEnd=7):
"""
Takes one metric or a wildcard seriesList, followed by a quoted string with the
length of time (See ``from / until`` in the :doc:`Render API <render_api>` for examples of time formats).
Also takes a start multiplier and end multiplier for the length of time
create a seriesList which is composed the original metric series stacked with time shifts
starting time shifts from the start multiplier through the end multiplier
Useful for looking at history, or feeding into averageSeries or stddevSeries.
Example:
.. code-block:: none
&target=timeStack(Sales.widgets.largeBlue,"1d",0,7) # create a series for today and each of the previous 7 days
"""
# Default to negative. parseTimeOffset defaults to +
if timeShiftUnit[0].isdigit():
timeShiftUnit = '-' + timeShiftUnit
delta = parseTimeOffset(timeShiftUnit)
if len(seriesList) < 1:
return []
series = seriesList[0]
results = []
timeShiftStartint = int(timeShiftStart)
timeShiftEndint = int(timeShiftEnd)
for shft in range(timeShiftStartint,timeShiftEndint):
myContext = requestContext.copy()
myContext['prefetch'] = {}
innerDelta = delta * shft
myContext['startTime'] = requestContext['startTime'] + innerDelta
myContext['endTime'] = requestContext['endTime'] + innerDelta
for shiftedSeries in evaluateTarget(myContext, requestContext['args'][0]):
shiftedSeries.tags['timeShiftUnit'] = timeShiftUnit
shiftedSeries.tags['timeShift'] = shft
shiftedSeries.name = 'timeShift(%s, %s, %s)' % (shiftedSeries.name, timeShiftUnit,shft)
shiftedSeries.pathExpression = shiftedSeries.name
shiftedSeries.start = series.start
shiftedSeries.end = series.end
results.append(shiftedSeries)
return results
timeStack.group = 'Transform'
timeStack.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('timeShiftUnit', ParamTypes.interval, default='1d', suggestions=['1h', '6h', '12h', '1d', '2d', '7d', '14d', '30d']),
Param('timeShiftStart', ParamTypes.integer, default=0),
Param('timeShiftEnd', ParamTypes.integer, default=7),
]
def timeShift(requestContext, seriesList, timeShift, resetEnd=True, alignDST=False):
"""
Takes one metric or a wildcard seriesList, followed by a quoted string with the
length of time (See ``from / until`` in the :doc:`Render API <render_api>` for examples of time formats).
Draws the selected metrics shifted in time. If no sign is given, a minus sign ( - ) is
implied which will shift the metric back in time. If a plus sign ( + ) is given, the
metric will be shifted forward in time.
Will reset the end date range automatically to the end of the base stat unless
resetEnd is False. Example case is when you timeshift to last week and have the graph
date range set to include a time in the future, will limit this timeshift to pretend
ending at the current time. If resetEnd is False, will instead draw full range including
future time.
Because time is shifted by a fixed number of seconds, comparing a time period with DST to
a time period without DST, and vice-versa, will result in an apparent misalignment. For
example, 8am might be overlaid with 7am. To compensate for this, use the alignDST option.
Useful for comparing a metric against itself at a past periods or correcting data
stored at an offset.
Example:
.. code-block:: none
&target=timeShift(Sales.widgets.largeBlue,"7d")
&target=timeShift(Sales.widgets.largeBlue,"-7d")
&target=timeShift(Sales.widgets.largeBlue,"+1h")
"""
# Default to negative. parseTimeOffset defaults to +
if timeShift[0].isdigit():
timeShift = '-' + timeShift
delta = parseTimeOffset(timeShift)
myContext = requestContext.copy()
myContext['prefetch'] = {}
myContext['startTime'] = requestContext['startTime'] + delta
myContext['endTime'] = requestContext['endTime'] + delta
if alignDST:
def localDST(dt):
return time.localtime(time.mktime(dt.timetuple())).tm_isdst
reqStartDST = localDST(requestContext['startTime'])
reqEndDST = localDST(requestContext['endTime'])
myStartDST = localDST(myContext['startTime'])
myEndDST = localDST(myContext['endTime'])
dstOffset = timedelta(hours=0)
# If the requestContext is entirely in DST, and we are entirely NOT in DST
if ((reqStartDST and reqEndDST) and (not myStartDST and not myEndDST)):
dstOffset = timedelta(hours=1)
# Or if the requestContext is entirely NOT in DST, and we are entirely in DST
elif ((not reqStartDST and not reqEndDST) and (myStartDST and myEndDST)):
dstOffset = timedelta(hours=-1)
# Otherwise, we don't do anything, because it would be visually confusing
myContext['startTime'] += dstOffset
myContext['endTime'] += dstOffset
results = []
if len(seriesList) < 1:
return []
series = seriesList[0]
for shiftedSeries in evaluateTarget(myContext, requestContext['args'][0]):
shiftedSeries.tags['timeShift'] = timeShift
shiftedSeries.name = 'timeShift(%s, "%s")' % (shiftedSeries.name, timeShift)
if resetEnd:
shiftedSeries.end = series.end
else:
shiftedSeries.end = shiftedSeries.end - shiftedSeries.start + series.start
shiftedSeries.start = series.start
results.append(shiftedSeries)
return results
timeShift.group = 'Transform'
timeShift.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('timeShift', ParamTypes.interval, required=True, suggestions=['1h', '6h', '12h', '1d', '2d', '7d', '14d', '30d']),
Param('resetEnd', ParamTypes.boolean, default=True),
Param('alignDst', ParamTypes.boolean, default=False),
]
def timeSlice(requestContext, seriesList, startSliceAt, endSliceAt="now"):
"""
Takes one metric or a wildcard metric, followed by a quoted string with the
time to start the line and another quoted string with the time to end the line.
The start and end times are inclusive. See ``from / until`` in the :doc:`Render API <render_api>`
for examples of time formats.
Useful for filtering out a part of a series of data from a wider range of
data.
Example:
.. code-block:: none
&target=timeSlice(network.core.port1,"00:00 20140101","11:59 20140630")
&target=timeSlice(network.core.port1,"12:00 20140630","now")
"""
results = []
start = time.mktime(parseATTime(startSliceAt).timetuple())
end = time.mktime(parseATTime(endSliceAt).timetuple())
for slicedSeries in seriesList:
slicedSeries.tags['timeSliceStart'] = int(start)
slicedSeries.tags['timeSliceEnd'] = int(end)
slicedSeries.name = 'timeSlice(%s, %s, %s)' % (slicedSeries.name, int(start), int(end))
curr = time.mktime(requestContext["startTime"].timetuple())
for i, v in enumerate(slicedSeries):
if v is None or curr < start or curr > end:
slicedSeries[i] = None
curr += slicedSeries.step
results.append(slicedSeries)
return results
timeSlice.group = 'Transform'
timeSlice.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('startSliceAt', ParamTypes.date, required=True),
Param('endSliceAt', ParamTypes.date, default='now'),
]
def constantLine(requestContext, value):
"""
Takes a float F.
Draws a horizontal line at value F across the graph.
Example:
.. code-block:: none
&target=constantLine(123.456)
"""
name = "constantLine(%s)" % str(value)
start = int(epoch( requestContext['startTime'] ) )
end = int(epoch( requestContext['endTime'] ) )
step = int((end - start) / 2.0)
series = TimeSeries(str(value), start, end, step, [value, value, value], xFilesFactor=requestContext.get('xFilesFactor'))
series.pathExpression = name
return [series]
constantLine.group = 'Special'
constantLine.params = [
Param('value', ParamTypes.float, required=True),
]
def aggregateLine(requestContext, seriesList, func='average', keepStep=False):
"""
Takes a metric or wildcard seriesList and draws a horizontal line
based on the function applied to each series.
If the optional keepStep parameter is set to True, the result will
have the same time period and step as the source series.
Note: By default, the graphite renderer consolidates data points by
averaging data points over time. If you are using the 'min' or 'max'
function for aggregateLine, this can cause an unusual gap in the
line drawn by this function and the data itself. To fix this, you
should use the consolidateBy() function with the same function
argument you are using for aggregateLine. This will ensure that the
proper data points are retained and the graph should line up
correctly.
Example:
.. code-block:: none
&target=aggregateLine(server01.connections.total, 'avg')
&target=aggregateLine(server*.connections.total, 'avg')
"""
aggFunc = getAggFunc(func)
results = []
for series in seriesList:
value = aggFunc(series)
if value is not None:
name = 'aggregateLine(%s, %g)' % (series.name, value)
else:
name = 'aggregateLine(%s, None)' % (series.name)
if keepStep:
aggSeries = series.copy(name=name, values=[value] * len(series))
else:
[aggSeries] = constantLine(requestContext, value)
aggSeries.name = name
aggSeries.pathExpression = name
results.append(aggSeries)
return results
aggregateLine.group = 'Calculate'
aggregateLine.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('func', ParamTypes.aggFunc, default='average'),
Param('keepStep', ParamTypes.boolean, default=False),
]
def verticalLine(requestContext, ts, label=None, color=None):
"""
Takes a timestamp string ts.
Draws a vertical line at the designated timestamp with optional
'label' and 'color'. Supported timestamp formats include both
relative (e.g. -3h) and absolute (e.g. 16:00_20110501) strings,
such as those used with ``from`` and ``until`` parameters. When
set, the 'label' will appear in the graph legend.
Note: Any timestamps defined outside the requested range will
raise a 'ValueError' exception.
Example:
.. code-block:: none
&target=verticalLine("12:3420131108","event","blue")
&target=verticalLine("16:00_20110501","event")
&target=verticalLine("-5mins")
"""
ts = int(timestamp( parseATTime(ts, requestContext['tzinfo']) ))
start = int(timestamp( requestContext['startTime'] ))
end = int(timestamp( requestContext['endTime'] ))
if ts < start:
raise InputParameterError("verticalLine(): timestamp %s exists before start of range" % ts)
elif ts > end:
raise InputParameterError("verticalLine(): timestamp %s exists after end of range" % ts)
start = end = ts
step = 1.0
series = TimeSeries(label, start, end, step, [1.0, 1.0], xFilesFactor=requestContext.get('xFilesFactor'))
series.options['drawAsInfinite'] = True
if color:
series.color = color
return [series]
verticalLine.group = 'Graph'
verticalLine.params = [
Param('ts', ParamTypes.date, required=True),
Param('label', ParamTypes.string),
Param('color', ParamTypes.string),
]
def threshold(requestContext, value, label=None, color=None):
"""
Takes a float F, followed by a label (in double quotes) and a color.
(See ``bgcolor`` in the :doc:`Render API <render_api>` for valid color names & formats.)
Draws a horizontal line at value F across the graph.
Example:
.. code-block:: none
&target=threshold(123.456, "omgwtfbbq", "red")
"""
series = constantLine(requestContext, value)[0]
if label:
series.name = label
if color:
series.color = color
return [series]
threshold.group = 'Graph'
threshold.params = [
Param('value', ParamTypes.float, required=True),
Param('label', ParamTypes.string),
Param('color', ParamTypes.string),
]
def transformNull(requestContext, seriesList, default=0, referenceSeries=None):
"""
Takes a metric or wildcard seriesList and replaces null values with the value
specified by `default`. The value 0 used if not specified. The optional
referenceSeries, if specified, is a metric or wildcard series list that governs
which time intervals nulls should be replaced. If specified, nulls are replaced
only in intervals where a non-null is found for the same interval in any of
referenceSeries. This method compliments the drawNullAsZero function in
graphical mode, but also works in text-only mode.
Example:
.. code-block:: none
&target=transformNull(webapp.pages.*.views,-1)
This would take any page that didn't have values and supply negative 1 as a default.
Any other numeric value may be used as well.
"""
def transform(v, d):
if v is None: return d
else: return v
if referenceSeries:
defaults = [default if any(v is not None for v in x) else None for x in izip_longest(*referenceSeries)]
else:
defaults = None
for series in seriesList:
series.tags['transformNull'] = default
if referenceSeries:
series.tags['referenceSeries'] = 1
if referenceSeries:
series.name = "transformNull(%s,%g,referenceSeries)" % (series.name, default)
else:
series.name = "transformNull(%s,%g)" % (series.name, default)
series.pathExpression = series.name
if defaults:
values = [transform(v, d) for v, d in izip_longest(series, defaults)]
else:
values = [transform(v, default) for v in series]
series.extend(values)
del series[:len(values)]
return seriesList
transformNull.group = 'Transform'
transformNull.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('default', ParamTypes.float, default=0),
Param('referenceSeries', ParamTypes.seriesList),
]
def isNonNull(requestContext, seriesList):
"""
Takes a metric or wildcard seriesList and counts up the number of non-null
values. This is useful for understanding the number of metrics that have data
at a given point in time (i.e. to count which servers are alive).
Example:
.. code-block:: none
&target=isNonNull(webapp.pages.*.views)
Returns a seriesList where 1 is specified for non-null values, and
0 is specified for null values.
"""
def transform(v):
if v is None: return 0
else: return 1
for series in seriesList:
series.tags['isNonNull'] = 1
series.name = "isNonNull(%s)" % (series.name)
series.pathExpression = series.name
values = [transform(v) for v in series]
series.extend(values)
del series[:len(values)]
return seriesList
isNonNull.group = 'Transform'
isNonNull.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def identity(requestContext, name):
"""
Identity function:
Returns datapoints where the value equals the timestamp of the datapoint.
Useful when you have another series where the value is a timestamp, and
you want to compare it to the time of the datapoint, to render an age
Example:
.. code-block:: none
&target=identity("The.time.series")
This would create a series named "The.time.series" that contains points where
x(t) == t.
"""
step = 60
start = int(epoch(requestContext["startTime"]))
end = int(epoch(requestContext["endTime"]))
values = list(range(start, end, step))
series = TimeSeries(name, start, end, step, values, xFilesFactor=requestContext.get('xFilesFactor'))
series.pathExpression = 'identity("%s")' % name
return [series]
identity.group = 'Calculate'
identity.params = [
Param('name', ParamTypes.string, required=True),
]
def countSeries(requestContext, *seriesLists):
"""
Draws a horizontal line representing the number of nodes found in the seriesList.
.. code-block:: none
&target=countSeries(carbon.agents.*.*)
"""
if seriesLists:
(seriesList,start,end,step) = normalize(seriesLists)
name = "countSeries(%s)" % formatPathExpressions(seriesList)
values = ( int(len(row)) for row in izip_longest(*seriesList) )
series = TimeSeries(name,start,end,step,values, xFilesFactor=requestContext.get('xFilesFactor'))
series.pathExpression = name
else:
series = constantLine(requestContext, 0).pop()
series.pathExpression = "countSeries()"
return [series]
countSeries.group = 'Combine'
countSeries.params = [
Param('seriesLists', ParamTypes.seriesList, multiple=True),
]
countSeries.aggregator = True
def group(requestContext, *seriesLists):
"""
Takes an arbitrary number of seriesLists and adds them to a single seriesList. This is used
to pass multiple seriesLists to a function which only takes one
"""
seriesGroup = []
for s in seriesLists:
seriesGroup.extend(s)
return seriesGroup
group.group = 'Combine'
group.params = [
Param('seriesLists', ParamTypes.seriesList, multiple=True),
]
def mapSeries(requestContext, seriesList, *mapNodes):
"""
Short form: ``map()``
Takes a seriesList and maps it to a list of seriesList. Each seriesList has the
given mapNodes in common.
.. note:: This function is not very useful alone. It should be used with :py:func:`reduceSeries`
.. code-block:: none
mapSeries(servers.*.cpu.*,1) =>
[
servers.server1.cpu.*,
servers.server2.cpu.*,
...
servers.serverN.cpu.*
]
Each node may be an integer referencing a node in the series name or a string identifying a tag.
"""
metaSeries = {}
keys = []
for series in seriesList:
key = aggKey(series, mapNodes)
if key not in metaSeries:
metaSeries[key] = [series]
keys.append(key)
else:
metaSeries[key].append(series)
return [ metaSeries[k] for k in keys ]
mapSeries.group = 'Combine'
mapSeries.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('mapNodes', ParamTypes.nodeOrTag, required=True, multiple=True),
]
def reduceSeries(requestContext, seriesLists, reduceFunction, reduceNode, *reduceMatchers):
"""
Short form: ``reduce()``
Takes a list of seriesLists and reduces it to a list of series by means of the reduceFunction.
Reduction is performed by matching the reduceNode in each series against the list of
reduceMatchers. Then each series is passed to the reduceFunction as arguments in the order
given by reduceMatchers. The reduceFunction should yield a single series.
The resulting list of series are aliased so that they can easily be nested in other functions.
**Example**: Map/Reduce asPercent(bytes_used,total_bytes) for each server
Assume that metrics in the form below exist:
.. code-block:: none
servers.server1.disk.bytes_used
servers.server1.disk.total_bytes
servers.server2.disk.bytes_used
servers.server2.disk.total_bytes
servers.server3.disk.bytes_used
servers.server3.disk.total_bytes
...
servers.serverN.disk.bytes_used
servers.serverN.disk.total_bytes
To get the percentage of disk used for each server:
.. code-block:: none
reduceSeries(mapSeries(servers.*.disk.*,1),"asPercent",3,"bytes_used","total_bytes") =>
alias(asPercent(servers.server1.disk.bytes_used,servers.server1.disk.total_bytes),"servers.server1.disk.reduce.asPercent"),
alias(asPercent(servers.server2.disk.bytes_used,servers.server2.disk.total_bytes),"servers.server2.disk.reduce.asPercent"),
alias(asPercent(servers.server3.disk.bytes_used,servers.server3.disk.total_bytes),"servers.server3.disk.reduce.asPercent"),
...
alias(asPercent(servers.serverN.disk.bytes_used,servers.serverN.disk.total_bytes),"servers.serverN.disk.reduce.asPercent")
In other words, we will get back the following metrics::
servers.server1.disk.reduce.asPercent
servers.server2.disk.reduce.asPercent
servers.server3.disk.reduce.asPercent
...
servers.serverN.disk.reduce.asPercent
.. seealso:: :py:func:`mapSeries`
"""
metaSeries = {}
keys = []
for seriesList in seriesLists:
for series in seriesList:
nodes = series.name.split('.')
node = nodes[reduceNode]
reduceSeriesName = '.'.join(nodes[0:reduceNode]) + '.reduce.' + reduceFunction
if node in reduceMatchers:
if reduceSeriesName not in metaSeries:
metaSeries[reduceSeriesName] = [None] * len(reduceMatchers)
keys.append(reduceSeriesName)
i = reduceMatchers.index(node)
metaSeries[reduceSeriesName][i] = series
for key in keys:
metaSeries[key] = SeriesFunction(reduceFunction)(requestContext,*[[l] for l in metaSeries[key]])[0]
metaSeries[key].name = key
return [ metaSeries[key] for key in keys ]
reduceSeries.group = 'Combine'
reduceSeries.params = [
Param('seriesLists', ParamTypes.seriesLists, required=True),
Param('reduceFunction', ParamTypes.string, required=True),
Param('reduceNode', ParamTypes.node, required=True),
Param('reduceMatchers', ParamTypes.string, required=True, multiple=True),
]
def applyByNode(requestContext, seriesList, nodeNum, templateFunction, newName=None):
"""
Takes a seriesList and applies some complicated function (described by a string), replacing templates with unique
prefixes of keys from the seriesList (the key is all nodes up to the index given as `nodeNum`).
If the `newName` parameter is provided, the name of the resulting series will be given by that parameter, with any
"%" characters replaced by the unique prefix.
Example:
.. code-block:: none
&target=applyByNode(servers.*.disk.bytes_free,1,"divideSeries(%.disk.bytes_free,sumSeries(%.disk.bytes_*))")
Would find all series which match `servers.*.disk.bytes_free`, then trim them down to unique series up to the node
given by nodeNum, then fill them into the template function provided (replacing % by the prefixes).
Additional Examples:
Given keys of
- `stats.counts.haproxy.web.2XX`
- `stats.counts.haproxy.web.3XX`
- `stats.counts.haproxy.web.5XX`
- `stats.counts.haproxy.microservice.2XX`
- `stats.counts.haproxy.microservice.3XX`
- `stats.counts.haproxy.microservice.5XX`
The following will return the rate of 5XX's per service:
.. code-block:: none
applyByNode(stats.counts.haproxy.*.*XX, 3, "asPercent(%.5XX, sumSeries(%.*XX))", "%.pct_5XX")
The output series would have keys `stats.counts.haproxy.web.pct_5XX` and `stats.counts.haproxy.microservice.pct_5XX`.
"""
prefixes = set()
for series in seriesList:
prefix = '.'.join(series.name.split('.')[:nodeNum + 1])
prefixes.add(prefix)
results = []
newContext = requestContext.copy()
newContext['prefetch'] = {}
for prefix in sorted(prefixes):
for resultSeries in evaluateTarget(newContext, templateFunction.replace('%', prefix)):
if newName:
resultSeries.name = newName.replace('%', prefix)
resultSeries.pathExpression = prefix
resultSeries.start = series.start
resultSeries.end = series.end
results.append(resultSeries)
return results
applyByNode.group = 'Combine'
applyByNode.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('nodeNum', ParamTypes.node, required=True),
Param('templateFunction', ParamTypes.string, required=True),
Param('newName', ParamTypes.string),
]
def groupByNode(requestContext, seriesList, nodeNum, callback='average'):
"""
Takes a serieslist and maps a callback to subgroups within as defined by a common node
.. code-block:: none
&target=groupByNode(ganglia.by-function.*.*.cpu.load5,2,"sumSeries")
Would return multiple series which are each the result of applying the "sumSeries" function
to groups joined on the second node (0 indexed) resulting in a list of targets like
.. code-block:: none
sumSeries(ganglia.by-function.server1.*.cpu.load5),sumSeries(ganglia.by-function.server2.*.cpu.load5),...
Node may be an integer referencing a node in the series name or a string identifying a tag.
This is an alias for using :py:func:`groupByNodes <groupByNodes>` with a single node.
"""
return groupByNodes(requestContext, seriesList, callback, nodeNum)
groupByNode.group = 'Combine'
groupByNode.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('nodeNum', ParamTypes.nodeOrTag, required=True),
Param('callback', ParamTypes.aggOrSeriesFunc, default='average'),
]
def groupByNodes(requestContext, seriesList, callback, *nodes):
"""
Takes a serieslist and maps a callback to subgroups within as defined by multiple nodes
.. code-block:: none
&target=groupByNodes(ganglia.server*.*.cpu.load*,"sum",1,4)
Would return multiple series which are each the result of applying the "sum" aggregation
to groups joined on the nodes' list (0 indexed) resulting in a list of targets like
.. code-block:: none
sumSeries(ganglia.server1.*.cpu.load5),sumSeries(ganglia.server1.*.cpu.load10),sumSeries(ganglia.server1.*.cpu.load15),sumSeries(ganglia.server2.*.cpu.load5),sumSeries(ganglia.server2.*.cpu.load10),sumSeries(ganglia.server2.*.cpu.load15),...
This function can be used with all aggregation functions supported by
:py:func:`aggregate <aggregate>`: ``average``, ``median``, ``sum``, ``min``, ``max``, ``diff``,
``stddev``, ``range`` & ``multiply``.
Each node may be an integer referencing a node in the series name or a string identifying a tag.
.. code-block:: none
&target=seriesByTag("name=~cpu.load.*", "server=~server[1-9]+", "datacenter=~dc[1-9]+")|groupByNodes("average", "datacenter", 1)
# will produce output series like
# dc1.load5, dc2.load5, dc1.load10, dc2.load10
This complements :py:func:`aggregateWithWildcards <aggregateWithWildcards>` which takes a list of wildcard nodes.
"""
metaSeries = {}
keys = []
for series in seriesList:
key = aggKey(series, nodes)
if key not in metaSeries:
metaSeries[key] = [series]
keys.append(key)
else:
metaSeries[key].append(series)
for key in metaSeries.keys():
if callback in SeriesFunctions:
metaSeries[key] = SeriesFunctions[callback](requestContext, metaSeries[key])[0]
else:
metaSeries[key] = aggregate(requestContext, metaSeries[key], callback)[0]
metaSeries[key].name = key
return [ metaSeries[key] for key in keys ]
groupByNodes.group = 'Combine'
groupByNodes.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('callback', ParamTypes.aggOrSeriesFunc, required=True),
Param('nodes', ParamTypes.nodeOrTag, multiple=True),
]
def exclude(requestContext, seriesList, pattern):
"""
Takes a metric or a wildcard seriesList, followed by a regular expression
in double quotes. Excludes metrics that match the regular expression.
Example:
.. code-block:: none
&target=exclude(servers*.instance*.threads.busy,"server02")
"""
regex = re.compile(pattern)
return [s for s in seriesList if not regex.search(s.name)]
exclude.group = 'Filter Series'
exclude.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('pattern', ParamTypes.string, required=True),
]
def grep(requestContext, seriesList, pattern):
"""
Takes a metric or a wildcard seriesList, followed by a regular expression
in double quotes. Excludes metrics that don't match the regular expression.
Example:
.. code-block:: none
&target=grep(servers*.instance*.threads.busy,"server02")
"""
regex = re.compile(pattern)
return [s for s in seriesList if regex.search(s.name)]
grep.group = 'Filter Series'
grep.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('pattern', ParamTypes.string, required=True),
]
def smartSummarize(requestContext, seriesList, intervalString, func='sum', alignTo=None):
"""
Smarter version of summarize.
The alignToFrom boolean parameter has been replaced by alignTo and no longer has any effect.
Alignment can be to years, months, weeks, days, hours, and minutes.
This function can be used with aggregation functions ``average``, ``median``, ``sum``, ``min``,
``max``, ``diff``, ``stddev``, ``count``, ``range``, ``multiply`` & ``last``.
"""
if isinstance(alignTo, bool):
log.info("Deprecated parameter 'alignToFrom' is being ignored.")
else:
# Adjust the start time aligning it according to interval unit
if alignTo is not None:
alignToUnit = getUnitString(alignTo)
requestContext = requestContext.copy()
requestContext['prefetch'] = {}
s = requestContext['startTime']
if alignToUnit == YEARS_STRING:
requestContext['startTime'] = datetime(s.year, 1, 1, tzinfo = s.tzinfo)
elif alignToUnit == MONTHS_STRING:
requestContext['startTime'] = datetime(s.year, s.month, 1, tzinfo = s.tzinfo)
elif alignToUnit == WEEKS_STRING:
isoWeekDayToAlignTo = 1 if alignTo[-1].isalpha() else int(alignTo[-1])
daysTosubtract = s.isoweekday() - isoWeekDayToAlignTo
if daysTosubtract < 0: daysTosubtract += 7
requestContext['startTime'] = datetime(s.year, s.month, s.day, tzinfo = s.tzinfo) - timedelta(days = daysTosubtract)
elif alignToUnit == DAYS_STRING:
requestContext['startTime'] = datetime(s.year, s.month, s.day, tzinfo = s.tzinfo)
elif alignToUnit == HOURS_STRING:
requestContext['startTime'] = datetime(s.year, s.month, s.day, s.hour, tzinfo = s.tzinfo)
elif alignToUnit == MINUTES_STRING:
requestContext['startTime'] = datetime(s.year, s.month, s.day, s.hour, s.minute, tzinfo = s.tzinfo)
elif alignToUnit == SECONDS_STRING:
requestContext['startTime'] = datetime(s.year, s.month, s.day, s.hour, s.minute, s.second, tzinfo = s.tzinfo)
# Ignore the originally fetched data and pull new using the modified requestContext
seriesList = evaluateTarget(requestContext, requestContext['args'][0])
results = []
delta = parseTimeOffset(intervalString)
interval = delta.seconds + (delta.days * 86400)
for series in seriesList:
(newValues, alignedEnd) = _summarizeValues(series, func, interval)
series.tags['smartSummarize'] = intervalString
series.tags['smartSummarizeFunction'] = func
newName = "smartSummarize(%s, \"%s\", \"%s\")" % (series.name, intervalString, func)
newSeries = series.copy(name=newName, end=alignedEnd, step=interval, values=newValues)
results.append(newSeries)
return results
smartSummarize.group = 'Transform'
smartSummarize.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('intervalString', ParamTypes.interval, required=True, suggestions=['10min', '1h', '1d']),
Param('func', ParamTypes.aggFunc, default='sum'),
# the options True and False are only part of this list for backwards
# compatibility and get ignored if specified
Param('alignTo', ParamTypes.string, options=[None, YEARS_STRING, MONTHS_STRING, WEEKS_STRING, DAYS_STRING, HOURS_STRING, MINUTES_STRING, SECONDS_STRING, True, False]),
]
def summarize(requestContext, seriesList, intervalString, func='sum', alignToFrom=False):
"""
Summarize the data into interval buckets of a certain size.
By default, the contents of each interval bucket are summed together. This is
useful for counters where each increment represents a discrete event and
retrieving a "per X" value requires summing all the events in that interval.
Specifying 'average' instead will return the mean for each bucket, which can be more
useful when the value is a gauge that represents a certain value in time.
This function can be used with aggregation functions ``average``, ``median``, ``sum``, ``min``,
``max``, ``diff``, ``stddev``, ``count``, ``range``, ``multiply`` & ``last``.
By default, buckets are calculated by rounding to the nearest interval. This
works well for intervals smaller than a day. For example, 22:32 will end up
in the bucket 22:00-23:00 when the interval=1hour.
Passing alignToFrom=true will instead create buckets starting at the from
time. In this case, the bucket for 22:32 depends on the from time. If
from=6:30 then the 1hour bucket for 22:32 is 22:30-23:30.
Example:
.. code-block:: none
&target=summarize(counter.errors, "1hour") # total errors per hour
&target=summarize(nonNegativeDerivative(gauge.num_users), "1week") # new users per week
&target=summarize(queue.size, "1hour", "avg") # average queue size per hour
&target=summarize(queue.size, "1hour", "max") # maximum queue size during each hour
&target=summarize(metric, "13week", "avg", true)&from=midnight+20100101 # 2010 Q1-4
"""
results = []
delta = parseTimeOffset(intervalString)
interval = delta.seconds + (delta.days * 86400)
for series in seriesList:
if alignToFrom:
newStart = series.start
newEnd = series.end
else:
newStart = series.start - (series.start % interval)
newEnd = series.end - (series.end % interval) + interval
(newValues, alignedEnd) = _summarizeValues(series, func, interval, newStart, newEnd)
if alignToFrom:
newEnd = alignedEnd
series.tags['summarize'] = intervalString
series.tags['summarizeFunction'] = func
newName = "summarize(%s, \"%s\", \"%s\"%s)" % (series.name, intervalString, func, alignToFrom and ", true" or "")
newSeries = series.copy(name=newName, start=newStart, end=newEnd, step=interval, values=newValues)
results.append(newSeries)
return results
summarize.group = 'Transform'
summarize.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('intervalString', ParamTypes.interval, required=True, suggestions=['10min', '1h', '1d']),
Param('func', ParamTypes.aggFunc, default='sum'),
Param('alignToFrom', ParamTypes.boolean, default=False),
]
def _summarizeValues(series, func, interval, newStart=None, newEnd=None):
if newStart is None:
newStart = series.start
if newEnd is None:
newEnd = series.end
aggFunc = getAggFunc(func)
timestamps = list(range( int(series.start), int(series.end), int(series.step)))
datapoints = list(series)
intervalPoints = interval / series.step
i = 0
numPoints = min(len(timestamps), len(datapoints))
newValues = []
timestamp_ = newStart
while timestamp_ < newEnd:
s = i
nonNull = 0
while i < numPoints and timestamps[i] < timestamp_ + interval:
if timestamps[i] <= timestamp_:
s = i
if timestamps[i] >= timestamp_ and datapoints[i] is not None:
nonNull += 1
i += 1
if xff(nonNull, intervalPoints, series.xFilesFactor):
newValues.append(aggFunc(datapoints[s:i]))
else:
newValues.append(None)
timestamp_ += interval
return (newValues, timestamp_)
def hitcount(requestContext, seriesList, intervalString, alignToInterval = False):
"""
Estimate hit counts from a list of time series.
This function assumes the values in each time series represent
hits per second. It calculates hits per some larger interval
such as per day or per hour. This function is like summarize(),
except that it compensates automatically for different time scales
(so that a similar graph results from using either fine-grained
or coarse-grained records) and handles rarely-occurring events
gracefully.
"""
results = []
delta = parseTimeOffset(intervalString)
interval = int(delta.seconds + (delta.days * 86400))
if alignToInterval:
requestContext = requestContext.copy()
requestContext['prefetch'] = {}
s = requestContext['startTime']
if interval >= DAY:
requestContext['startTime'] = datetime(s.year, s.month, s.day, tzinfo = s.tzinfo)
elif interval >= HOUR:
requestContext['startTime'] = datetime(s.year, s.month, s.day, s.hour, tzinfo = s.tzinfo)
elif interval >= MINUTE:
requestContext['startTime'] = datetime(s.year, s.month, s.day, s.hour, s.minute, tzinfo = s.tzinfo)
# Ignore the originally fetched data and pull new using
# the modified requestContext.
seriesList = evaluateTarget(requestContext, requestContext['args'][0])
for series in seriesList:
intervalCount = int((series.end - series.start) // interval)
series.end = series.start + (intervalCount * interval) + interval
for series in seriesList:
step = int(series.step)
bucket_count = int(math.ceil(float(series.end - series.start) / interval))
buckets = [[] for _ in range(bucket_count)]
newStart = int(series.end - bucket_count * interval)
for i, value in enumerate(series):
if value is None:
continue
start_time = int(series.start + i * step)
start_bucket, start_mod = divmod(start_time - newStart, interval)
end_time = start_time + step
end_bucket, end_mod = divmod(end_time - newStart, interval)
if end_bucket >= bucket_count:
end_bucket = bucket_count - 1
end_mod = interval
if start_bucket == end_bucket:
# All of the hits go to a single bucket.
if start_bucket >= 0:
buckets[start_bucket].append(value * (end_mod - start_mod))
else:
# Spread the hits among 2 or more buckets.
if start_bucket >= 0:
buckets[start_bucket].append(value * (interval - start_mod))
hits_per_bucket = value * interval
for j in range(start_bucket + 1, end_bucket):
buckets[j].append(hits_per_bucket)
if end_mod > 0:
buckets[end_bucket].append(value * end_mod)
newValues = []
for bucket in buckets:
if bucket:
newValues.append( sum(bucket) )
else:
newValues.append(None)
series.tags['hitcount'] = intervalString
newName = 'hitcount(%s, "%s"%s)' % (series.name, intervalString, alignToInterval and ", true" or "")
newSeries = series.copy(name=newName, start=newStart, step=interval, values=newValues)
results.append(newSeries)
return results
hitcount.group = 'Transform'
hitcount.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('intervalString', ParamTypes.interval, required=True, suggestions=['10min', '1h', '1d']),
Param('alignToInterval', ParamTypes.boolean, default=False),
]
def timeFunction(requestContext, name, step=60):
"""
Short Alias: time()
Just returns the timestamp for each X value. T
Example:
.. code-block:: none
&target=time("The.time.series")
This would create a series named "The.time.series" that contains in Y the same
value (in seconds) as X.
Accepts optional second argument as 'step' parameter (default step is 60 sec)
"""
# TODO: align both startTime and endTime when creating the TimeSeries.
delta = timedelta(seconds=step)
when = requestContext["startTime"]
values = []
while when < requestContext["endTime"]:
values.append(time.mktime(when.timetuple()))
when += delta
series = TimeSeries(name,
int(time.mktime(requestContext["startTime"].timetuple())),
int(time.mktime(requestContext["endTime"].timetuple())),
step, values, xFilesFactor=requestContext.get('xFilesFactor'))
return [series]
timeFunction.group = 'Transform'
timeFunction.params = [
Param('name', ParamTypes.string, required=True),
Param('step', ParamTypes.integer, default=60),
]
def sinFunction(requestContext, name, amplitude=1, step=60):
"""
Short Alias: sin()
Just returns the sine of the current time. The optional amplitude parameter
changes the amplitude of the wave.
Example:
.. code-block:: none
&target=sin("The.time.series", 2)
This would create a series named "The.time.series" that contains sin(x)*2.
Accepts optional second argument as 'amplitude' parameter (default amplitude is 1)
Accepts optional third argument as 'step' parameter (default step is 60 sec)
"""
delta = timedelta(seconds=step)
when = requestContext["startTime"]
values = []
while when < requestContext["endTime"]:
values.append(math.sin(time.mktime(when.timetuple()))*amplitude)
when += delta
return [TimeSeries(name,
int(epoch(requestContext["startTime"])),
int(epoch(requestContext["endTime"])),
step, values, xFilesFactor=requestContext.get('xFilesFactor'))]
sinFunction.group = 'Transform'
sinFunction.params = [
Param('name', ParamTypes.string, required=True),
Param('amplitude', ParamTypes.integer, default=1),
Param('step', ParamTypes.integer, default=60),
]
def removeEmptySeries(requestContext, seriesList, xFilesFactor=None):
"""
Takes one metric or a wildcard seriesList.
Out of all metrics passed, draws only the metrics with not empty data
Example:
.. code-block:: none
&target=removeEmptySeries(server*.instance*.threads.busy)
Draws only live servers with not empty data.
`xFilesFactor` follows the same semantics as in Whisper storage schemas. Setting it to 0 (the
default) means that only a single value in the series needs to be non-null for it to be
considered non-empty, setting it to 1 means that all values in the series must be non-null.
A setting of 0.5 means that at least half the values in the series must be non-null.
"""
xFilesFactor = xFilesFactor if xFilesFactor is not None else 0
return [ series for series in seriesList if xffValues(series, xFilesFactor) ]
removeEmptySeries.group = 'Filter Series'
removeEmptySeries.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('xFilesFactor', ParamTypes.float),
]
def unique(requestContext, *seriesLists):
"""
Takes an arbitrary number of seriesLists and returns unique series, filtered by name.
Example:
.. code-block:: none
&target=unique(mostDeviant(server.*.disk_free,5),lowestCurrent(server.*.disk_free,5))
Draws servers with low disk space, and servers with highly deviant disk space, but never the same series twice.
"""
newList = []
seenNames = set()
for seriesList in seriesLists:
for series in seriesList:
if series.name not in seenNames:
seenNames.add(series.name)
newList.append(series)
return newList
unique.group = 'Filter Series'
unique.params = [
Param('seriesLists', ParamTypes.seriesList, required=True, multiple=True),
]
def randomWalkFunction(requestContext, name, step=60):
"""
Short Alias: randomWalk()
Returns a random walk starting at 0. This is great for testing when there is
no real data in whisper.
Example:
.. code-block:: none
&target=randomWalk("The.time.series")
This would create a series named "The.time.series" that contains points where
x(t) == x(t-1)+random()-0.5, and x(0) == 0.
Accepts optional second argument as 'step' parameter (default step is 60 sec)
"""
delta = timedelta(seconds=step)
when = requestContext["startTime"]
values = []
current = 0
while when < requestContext["endTime"]:
values.append(current)
current += random.random() - 0.5
when += delta
return [TimeSeries(name,
int(epoch(requestContext["startTime"])),
int(epoch(requestContext["endTime"])),
step, values, xFilesFactor=requestContext.get('xFilesFactor'))]
randomWalkFunction.group = 'Special'
randomWalkFunction.params = [
Param('name', ParamTypes.string, required=True),
Param('step', ParamTypes.integer, default=60),
]
def seriesByTag(requestContext, *tagExpressions):
"""
Returns a SeriesList of series matching all the specified tag expressions.
Example:
.. code-block:: none
&target=seriesByTag("tag1=value1","tag2!=value2")
Returns a seriesList of all series that have tag1 set to value1, AND do not have tag2 set to value2.
Tags specifiers are strings, and may have the following formats:
.. code-block:: none
tag=spec tag value exactly matches spec
tag!=spec tag value does not exactly match spec
tag=~value tag value matches the regular expression spec
tag!=~spec tag value does not match the regular expression spec
Any tag spec that matches an empty value is considered to match series that don't have that tag.
At least one tag spec must require a non-empty value.
Regular expression conditions are treated as being anchored at the start of the value.
See :ref:`querying tagged series <querying-tagged-series>` for more detail.
"""
# the handling of seriesByTag is implemented in STORE.fetch
seriesByTag.group = 'Special'
seriesByTag.params = [
Param('tagExpressions', ParamTypes.string, required=True, multiple=True),
]
def groupByTags(requestContext, seriesList, callback, *tags):
"""
Takes a serieslist and maps a callback to subgroups within as defined by multiple tags
.. code-block:: none
&target=seriesByTag("name=cpu")|groupByTags("average","dc")
Would return multiple series which are each the result of applying the "averageSeries" function
to groups joined on the specified tags resulting in a list of targets like
.. code-block :: none
averageSeries(seriesByTag("name=cpu","dc=dc1")),averageSeries(seriesByTag("name=cpu","dc=dc2")),...
This function can be used with all aggregation functions supported by
:py:func:`aggregate <aggregate>`: ``average`` (or ``avg``), ``avg_zero``,
``median``, ``sum`` (or ``total``), ``min``, ``max``, ``diff``, ``stddev``, ``count``,
``range`` (or ``rangeOf``) , ``multiply`` & ``last`` (or ``current``).
"""
if STORE.tagdb is None:
log.info('groupByTags called but no TagDB configured')
return []
if not tags:
raise InputParameterError("groupByTags(): no tags specified")
# if all series have the same "name" tag use that for results, otherwise use the callback
# if we're grouping by name, then the name is always used (see below)
if 'name' not in tags:
names = set([series.tags['name'] for series in seriesList])
name = list(names)[0] if len(names) == 1 else callback
keys = []
metaSeries = {}
for series in seriesList:
# key is the metric path for the new series
if 'name' not in tags:
key = ';'.join([name] + sorted([tag + '=' + series.tags.get(tag, '') for tag in tags]))
else:
key = ';'.join([series.tags['name']] + sorted([tag + '=' + series.tags.get(tag, '') for tag in tags if tag != 'name']))
if key not in metaSeries:
metaSeries[key] = [series]
keys.append(key)
else:
metaSeries[key].append(series)
for key in keys:
if callback in SeriesFunctions:
metaSeries[key] = SeriesFunctions[callback](requestContext, metaSeries[key])[0]
else:
metaSeries[key] = aggregate(requestContext, metaSeries[key], callback)[0]
metaSeries[key].name = key
metaSeries[key].pathExpression = key
metaSeries[key].tags = STORE.tagdb.parse(key).tags
return [metaSeries[key] for key in keys]
groupByTags.group = 'Combine'
groupByTags.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('callback', ParamTypes.aggOrSeriesFunc, required=True),
Param('tags', ParamTypes.tag, required=True, multiple=True),
]
def aliasByTags(requestContext, seriesList, *tags):
"""
Takes a seriesList and applies an alias derived from one or more tags and/or nodes
.. code-block:: none
&target=seriesByTag("name=cpu")|aliasByTags("server","name")
This is an alias for :py:func:`aliasByNode <aliasByNode>`.
"""
return aliasByNode(requestContext, seriesList, *tags)
aliasByTags.group = 'Alias'
aliasByTags.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
Param('tags', ParamTypes.nodeOrTag, required=True, multiple=True),
]
def events(requestContext, *tags):
"""
Returns the number of events at this point in time. Usable with
drawAsInfinite.
Example:
.. code-block:: none
&target=events("tag-one", "tag-two")
&target=events("*")
Returns all events tagged as "tag-one" and "tag-two" and the second one
returns all events.
"""
step = 1
name = "events(\"" + "\", \"".join(tags) + "\")"
if tags == ("*",):
tags = None
start_timestamp = epoch(requestContext["startTime"])
start_timestamp = start_timestamp - start_timestamp % step
end_timestamp = epoch(requestContext["endTime"])
end_timestamp = end_timestamp - end_timestamp % step
points = (end_timestamp - start_timestamp) // step
events = models.Event.find_events(epoch_to_dt(start_timestamp),
epoch_to_dt(end_timestamp),
tags=tags)
values = [None] * points
for event in events:
event_timestamp = epoch(event.when)
value_offset = (event_timestamp - start_timestamp) // step
if values[value_offset] is None:
values[value_offset] = 1
else:
values[value_offset] += 1
result_series = TimeSeries(name, start_timestamp, end_timestamp, step, values, 'sum', xFilesFactor=requestContext.get('xFilesFactor'))
return [result_series]
events.group = 'Special'
events.params = [
Param('tags', ParamTypes.string, required=True, multiple=True),
]
def minMax(requestContext, seriesList):
"""
Applies the popular min max normalization technique, which takes
each point and applies the following normalization transformation
to it: normalized = (point - min) / (max - min).
Example:
.. code-block:: none
&target=minMax(Server.instance01.threads.busy)
"""
for series in seriesList:
series.name = "minMax(%s)" % (series.name)
series.pathExpression = series.name
min_val = safe.safeMin(series, default=0.0)
max_val = safe.safeMax(series, default=0.0)
for i, val in enumerate(series):
if series[i] is not None:
try:
series[i] = float(val - min_val) / (max_val - min_val)
except ZeroDivisionError:
series[i] = 0.0
return seriesList
minMax.group = 'Transform'
minMax.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def compressPeriodicGaps(requestContext, seriesList):
"""
Tries to intelligently remove periodic None's from series, recalculating start, stop and step values.
You can use `summarize(seriesList, '<desired step>', 'last')` function for that also, but this function trying to
guess desired step automatically. Can be used in case of fix metric with improper resolution.
Especially useful for derivative functions, which are not working with series with regular gaps.
Example:
.. code-block:: none
&target=compressPeriodicGaps(Server.instance01.threads.busy)
"""
resultList = []
for series in seriesList:
series.name = "compressPeriodicGaps(%s)" % series.name
series.pathExpression = series.name
resultList.append(_compressPeriodicGaps(series))
return resultList
compressPeriodicGaps.group = 'Transform'
compressPeriodicGaps.params = [
Param('seriesList', ParamTypes.seriesList, required=True),
]
def pieAverage(requestContext, series):
"""Return the average"""
return safe.safeDiv(safe.safeSum(series), safe.safeLen(series))
pieAverage.group = 'Pie'
pieAverage.params = [
Param('series', ParamTypes.series, required=True),
]
def pieMaximum(requestContext, series):
"""Return the maximum"""
return safe.safeMax(series)
pieMaximum.group = 'Pie'
pieMaximum.params = [
Param('series', ParamTypes.series, required=True),
]
def pieMinimum(requestContext, series):
"""Return the minimum"""
return safe.safeMin(series)
pieMinimum.group = 'Pie'
pieMinimum.params = [
Param('series', ParamTypes.series, required=True),
]
PieFunctions = {
'average': pieAverage,
'maximum': pieMaximum,
'minimum': pieMinimum,
}
SeriesFunctions = {
# Combine functions
'aggregate': aggregate,
'aggregateSeriesLists': aggregateSeriesLists,
'aggregateWithWildcards': aggregateWithWildcards,
'applyByNode': applyByNode,
'asPercent': asPercent,
'averageSeries': averageSeries,
'averageSeriesWithWildcards': averageSeriesWithWildcards,
'avg': averageSeries,
'countSeries': countSeries,
'diffSeries': diffSeries,
'diffSeriesLists': diffSeriesLists,
'divideSeries': divideSeries,
'divideSeriesLists': divideSeriesLists,
'group': group,
'groupByNode': groupByNode,
'groupByNodes' : groupByNodes,
'groupByTags': groupByTags,
'isNonNull': isNonNull,
'map': mapSeries,
'mapSeries': mapSeries,
'maxSeries': maxSeries,
'minSeries': minSeries,
'multiplySeries': multiplySeries,
'multiplySeriesLists': multiplySeriesLists,
'multiplySeriesWithWildcards': multiplySeriesWithWildcards,
'pct': asPercent,
'percentileOfSeries': percentileOfSeries,
'rangeOfSeries': rangeOfSeries,
'reduce': reduceSeries,
'reduceSeries': reduceSeries,
'stddevSeries': stddevSeries,
'sum': sumSeries,
'sumSeries': sumSeries,
'sumSeriesLists': sumSeriesLists,
'sumSeriesWithWildcards': sumSeriesWithWildcards,
'weightedAverage': weightedAverage,
# Transform functions
'add': add,
'absolute': absolute,
'compressPeriodicGaps': compressPeriodicGaps,
'delay': delay,
'derivative': derivative,
'exp': exp,
'hitcount': hitcount,
'integral': integral,
'integralByInterval' : integralByInterval,
'interpolate': interpolate,
'invert': invert,
'keepLastValue': keepLastValue,
'log': logarithm,
'logit': logit,
'minMax': minMax,
'nonNegativeDerivative': nonNegativeDerivative,
'offset': offset,
'offsetToZero': offsetToZero,
'perSecond': perSecond,
'pow': pow,
'powSeries': powSeries,
'round': roundFunction,
'scale': scale,
'scaleToSeconds': scaleToSeconds,
'sigmoid': sigmoid,
'smartSummarize': smartSummarize,
'squareRoot': squareRoot,
'summarize': summarize,
'timeShift': timeShift,
'timeSlice': timeSlice,
'timeStack': timeStack,
'transformNull': transformNull,
# Calculate functions
'aggregateLine': aggregateLine,
'exponentialMovingAverage': exponentialMovingAverage,
'holtWintersAberration': holtWintersAberration,
'holtWintersConfidenceArea': holtWintersConfidenceArea,
'holtWintersConfidenceBands': holtWintersConfidenceBands,
'holtWintersForecast': holtWintersForecast,
'linearRegression': linearRegression,
'movingAverage': movingAverage,
'movingMax': movingMax,
'movingMedian': movingMedian,
'movingMin': movingMin,
'movingSum': movingSum,
'movingWindow': movingWindow,
'nPercentile': nPercentile,
'stdev': stdev,
# Series Filter functions
'averageAbove': averageAbove,
'averageBelow': averageBelow,
'averageOutsidePercentile': averageOutsidePercentile,
'currentAbove': currentAbove,
'currentBelow': currentBelow,
'exclude': exclude,
'filterSeries': filterSeries,
'grep': grep,
'highest': highest,
'highestAverage': highestAverage,
'highestCurrent': highestCurrent,
'highestMax': highestMax,
'limit': limit,
'lowest': lowest,
'lowestAverage': lowestAverage,
'lowestCurrent': lowestCurrent,
'maximumAbove': maximumAbove,
'maximumBelow': maximumBelow,
'minimumAbove': minimumAbove,
'minimumBelow': minimumBelow,
'mostDeviant': mostDeviant,
'removeBetweenPercentile': removeBetweenPercentile,
'removeEmptySeries': removeEmptySeries,
'unique': unique,
'useSeriesAbove': useSeriesAbove,
# Data Filter functions
'removeAbovePercentile': removeAbovePercentile,
'removeAboveValue': removeAboveValue,
'removeBelowPercentile': removeBelowPercentile,
'removeBelowValue': removeBelowValue,
# Sorting functions
'sortBy': sortBy,
'sortByMaxima': sortByMaxima,
'sortByMinima': sortByMinima,
'sortByName': sortByName,
'sortByTotal': sortByTotal,
# Alias functions
'alias': alias,
'aliasByMetric': aliasByMetric,
'aliasByNode': aliasByNode,
'aliasByTags': aliasByTags,
'aliasQuery': aliasQuery,
'aliasSub': aliasSub,
'legendValue': legendValue,
'upper': toUpperCase,
'lower': toLowerCase,
# Graph functions
'alpha': alpha,
'areaBetween': areaBetween,
'color': color,
'dashed': dashed,
'drawAsInfinite': drawAsInfinite,
'lineWidth': lineWidth,
'secondYAxis': secondYAxis,
'stacked': stacked,
'threshold': threshold,
'verticalLine' : verticalLine,
# Special functions
'cactiStyle': cactiStyle,
'changed': changed,
'consolidateBy': consolidateBy,
'constantLine': constantLine,
'events': events,
'cumulative': cumulative,
'fallbackSeries': fallbackSeries,
'identity': identity,
"randomWalk": randomWalkFunction,
"randomWalkFunction": randomWalkFunction,
'setXFilesFactor': setXFilesFactor,
"sin": sinFunction,
"sinFunction": sinFunction,
'seriesByTag': seriesByTag,
'substr': substr,
'time': timeFunction,
'timeFunction': timeFunction,
'xFilesFactor': setXFilesFactor,
}
ParamTypes.aggOrSeriesFunc.setSeriesFuncs(SeriesFunctions)
|