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
|
static const char *RcsId = "$Id$";
//=====================================================================================================================
//
// file : zmqeventconsumer.cpp
//
// description : C++ classes for implementing the event consumer singleton class when used with zmq
//
// author(s) : E.Taurel
//
// original : 16 August 2011
//
// Copyright (C) : 2011,2012,2013,2014,2015
// European Synchrotron Radiation Facility
// BP 220, Grenoble 38043
// FRANCE
//
// This file is part of Tango.
//
// Tango is free software: you can redistribute it and/or modify it under the terms of the GNU
// Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Tango is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License along with Tango.
// If not, see <http://www.gnu.org/licenses/>.
//
// $Revision$
//
//
//====================================================================================================================
#include <tango.h>
#include <eventconsumer.h>
#include <stdio.h>
#include <assert.h>
#include <omniORB4/internal/giopStream.h>
#ifdef _TG_WINDOWS_
#include <winsock2.h>
#include <ws2tcpip.h>
#include <sys/timeb.h>
#include <process.h>
#else
#include <unistd.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <fcntl.h>
#include <arpa/inet.h>
#endif
using namespace CORBA;
namespace Tango {
ZmqEventConsumer *ZmqEventConsumer::_instance = NULL;
//omni_mutex EventConsumer::ev_consumer_inst_mutex;
/************************************************************************/
/* */
/* ZmqEventConsumer class */
/* ---------------- */
/* */
/************************************************************************/
ZmqEventConsumer::ZmqEventConsumer(ApiUtil *ptr) : EventConsumer(ptr),
omni_thread((void *)ptr),zmq_context(1),ctrl_socket_bound(false)
{
cout3 << "calling Tango::ZmqEventConsumer::ZmqEventConsumer() \n";
_instance = this;
//
// Initialize the var references
//
av = new AttributeValue();
av3 = new AttributeValue_3();
ac2 = new AttributeConfig_2();
ac3 = new AttributeConfig_3();
ac5 = new AttributeConfig_5();
adr = new AttDataReady();
dic = new DevIntrChange();
del = new DevErrorList();
start_undetached();
}
ZmqEventConsumer *ZmqEventConsumer::create()
{
omni_mutex_lock guard(ev_consumer_inst_mutex);
//
// check if the ZmqEventConsumer singleton exists, if so return it
//
if (_instance != NULL)
{
return _instance;
}
//
// ZmqEventConsumer singleton does not exist, create it
//
ApiUtil *ptr = ApiUtil::instance();
return new ZmqEventConsumer(ptr);
}
//-------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqEventConsumer::run_undetached()
//
// description :
// Main method for the ZMQ event system reciving thread
//
//-------------------------------------------------------------------------------------------------------------------
void *ZmqEventConsumer::run_undetached(TANGO_UNUSED(void *arg))
{
int linger = 0;
int reconnect_ivl = -1;
int send_hwm = SUB_SEND_HWM;
//
// Store thread ID
//
thread_id = self()->id();
//
// Create the subscriber socket used to receive heartbeats coming from different DS. This socket subscribe to
// everything because dedicated publishers are used to send the heartbeat events. This socket will be connected
// to all needed publishers
//
heartbeat_sub_sock = new zmq::socket_t(zmq_context,ZMQ_SUB);
heartbeat_sub_sock->setsockopt(ZMQ_LINGER,&linger,sizeof(linger));
try
{
heartbeat_sub_sock->setsockopt(ZMQ_RECONNECT_IVL,&reconnect_ivl,sizeof(reconnect_ivl));
}
catch (zmq::error_t &)
{
reconnect_ivl = 30000;
heartbeat_sub_sock->setsockopt(ZMQ_RECONNECT_IVL,&reconnect_ivl,sizeof(reconnect_ivl));
}
heartbeat_sub_sock->setsockopt(ZMQ_SNDHWM,&send_hwm,sizeof(send_hwm));
//
// Create the subscriber socket used to receive events coming from different DS. This socket subscribe to everything
// because dedicated publishers are used to send the heartbeat events. This socket will be connected to all needed
// publishers
//
event_sub_sock = new zmq::socket_t(zmq_context,ZMQ_SUB);
event_sub_sock->setsockopt(ZMQ_LINGER,&linger,sizeof(linger));
event_sub_sock->setsockopt(ZMQ_RECONNECT_IVL,&reconnect_ivl,sizeof(reconnect_ivl));
event_sub_sock->setsockopt(ZMQ_SNDHWM,&send_hwm,sizeof(send_hwm));
//
// Create the control socket (REQ/REP pattern) and binds it
//
control_sock = new zmq::socket_t(zmq_context,ZMQ_REP);
control_sock->setsockopt(ZMQ_LINGER,&linger,sizeof(linger));
control_sock->bind(CTRL_SOCK_ENDPOINT);
set_ctrl_sock_bound();
//
// Initialize poll set
//
zmq::pollitem_t *items = new zmq::pollitem_t [MAX_SOCKET_SUB];
int nb_poll_item = 3;
items[0].socket = *control_sock;
items[1].socket = *heartbeat_sub_sock;
items[2].socket = *event_sub_sock;
for (int loop = 0;loop < nb_poll_item;loop++)
{
items[loop].fd = 0;
items[loop].events = ZMQ_POLLIN;
items[loop].revents = 0;
}
//
// Enter the infinite loop
//
while(1)
{
zmq::message_t received_event_name,received_endian;
zmq::message_t received_call,received_event_data;
zmq::message_t received_ctrl;
//
// Init messages used by multicast event
//
zmq_msg_t mcast_received_event_name;
zmq_msg_t mcast_received_endian;
zmq_msg_t mcast_received_call;
zmq_msg_t mcast_received_event_data;
//
// Wait for message. The try/catch is usefull when the process is running under gdb control
//
try
{
zmq::poll(items,nb_poll_item,-1);
//cout << "Awaken !!!!!!!!" << endl;
}
catch(zmq::error_t &e)
{
if (e.num() == EINTR)
continue;
}
//
// Something received by the heartbeat socket ?
//
if (items[1].revents & ZMQ_POLLIN)
{
//cout << "For the heartbeat socket" << endl;
bool res;
try
{
res = heartbeat_sub_sock->recv(&received_event_name,ZMQ_DONTWAIT);
if (res == false)
{
print_error_message("First Zmq recv call on heartbeat socket returned false! De-synchronized event system?");
items[1].revents = 0;
continue;
}
res = heartbeat_sub_sock->recv(&received_endian,ZMQ_DONTWAIT);
if (res == false)
{
print_error_message("Second Zmq recv call on heartbeat socket returned false! De-synchronized event system?");
items[1].revents = 0;
continue;
}
res = heartbeat_sub_sock->recv(&received_call,ZMQ_DONTWAIT);
if (res == false)
{
print_error_message("Third Zmq recv call on heartbeat socket returned false! De-synchronized event system?");
items[1].revents = 0;
continue;
}
process_heartbeat(received_event_name,received_endian,received_call);
}
catch (zmq::error_t &e)
{
print_error_message("Zmq exception while receiving heartbeat data!");
cerr << "Error number: " << e.num() << ", error message: " << e.what() << endl;
items[1].revents = 0;
continue;
}
items[1].revents = 0;
}
//
// Something received by the event socket (TCP transport)?
//
if (items[2].revents & ZMQ_POLLIN)
{
//cout << "For the event socket" << endl;
bool res;
try
{
res = event_sub_sock->recv(&received_event_name,ZMQ_DONTWAIT);
if (res == false)
{
print_error_message("First Zmq recv call on event socket returned false! De-synchronized event system?");
items[2].revents = 0;
continue;
}
res = event_sub_sock->recv(&received_endian,ZMQ_DONTWAIT);
if (res == false)
{
print_error_message("Second Zmq recv call on event socket returned false! De-synchronized event system?");
items[2].revents = 0;
continue;
}
res = event_sub_sock->recv(&received_call,ZMQ_DONTWAIT);
if (res == false)
{
print_error_message("Third Zmq recv call on event socket returned false! De-synchronized event system?");
items[2].revents = 0;
continue;
}
res = event_sub_sock->recv(&received_event_data,ZMQ_DONTWAIT);
if (res == false)
{
print_error_message("Forth Zmq recv call on event socket returned false! De-synchronized event system?");
items[2].revents = 0;
continue;
}
process_event(received_event_name,received_endian,received_call,received_event_data);
}
catch (zmq::error_t &e)
{
print_error_message("Zmq exception while receiving event data!");
cerr << "Error number: " << e.num() << ", error message: " << e.what() << endl;
items[2].revents = 0;
continue;
}
items[2].revents = 0;
}
//
// Something received by the control socket?
//
if (items[0].revents & ZMQ_POLLIN)
{
//cout << "For the control socket" << endl;
control_sock->recv(&received_ctrl);
string ret_str;
bool ret = false;
try
{
ret = process_ctrl(received_ctrl,items,nb_poll_item);
ret_str = "OK";
}
catch (zmq::error_t &e)
{
ret_str = e.what();
}
catch (Tango::DevFailed &e)
{
ret_str = e.errors[0].desc;
}
zmq::message_t reply(ret_str.size());
::memcpy((void *)reply.data(),ret_str.data(),ret_str.size());
control_sock->send(reply);
if (ret == true)
{
delete heartbeat_sub_sock;
delete control_sock;
delete [] items;
break;
}
items[0].revents = 0;
}
//
// Something received by the event socket (mcast transport)?
//
// What is stored in the zmq::pollitem_t structure is the real C zmq socket, not the C++ zmq::socket_t class instance.
// There is no way to create a zmq::socket_t class instance from a C zmq socket. Only in 11/2012, some C++11 move
// ctor/assignment operator has been added to the socket_t class allowing creation of zmq::socket_t class from C zmq
// socket. Nevertheless, today (11/2012), it is still not official
//
for (int loop = 3;loop < nb_poll_item;loop++)
{
if (items[loop].revents & ZMQ_POLLIN)
{
zmq_msg_init(&mcast_received_event_name);
zmq_msg_init(&mcast_received_endian);
zmq_msg_init(&mcast_received_call);
zmq_msg_init(&mcast_received_event_data);
zmq_recvmsg(items[loop].socket,&mcast_received_event_name,0);
zmq_recvmsg(items[loop].socket,&mcast_received_endian,0);
zmq_recvmsg(items[loop].socket,&mcast_received_call,0);
zmq_recvmsg(items[loop].socket,&mcast_received_event_data,0);
process_event(mcast_received_event_name,mcast_received_endian,mcast_received_call,mcast_received_event_data);
zmq_msg_close(&mcast_received_event_name);
zmq_msg_close(&mcast_received_endian);
zmq_msg_close(&mcast_received_call);
zmq_msg_close(&mcast_received_event_data);
items[loop].revents = 0;
}
}
}
return (void *)NULL;
}
//--------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqEventConsumer::process_heartbeat()
//
// description :
// Process execution when a message has been received by the heartbeat socket
//
// argument :
// in :
// - received_event_name : The full event name
// - received_endian : The sender endianess
// - received_call : The call informations (oid - method name...)
//
//---------------------------------------------------------------------------------------------------------------------
void ZmqEventConsumer::process_heartbeat(zmq::message_t &received_event_name,zmq::message_t &received_endian,zmq::message_t &received_call)
{
//
// For debug and logging purposes
//
if (omniORB::trace(20))
{
omniORB::logger log;
log << "ZMQ: A heartbeat message has been received" << '\n';
}
if (omniORB::trace(30))
{
{
omniORB::logger log;
log << "ZMQ: Event name" << '\n';
}
omni::giopStream::dumpbuf((unsigned char *)received_event_name.data(),received_event_name.size());
{
omniORB::logger log;
log << "ZMQ: Endianess" << '\n';
}
omni::giopStream::dumpbuf((unsigned char *)received_endian.data(),received_endian.size());
{
omniORB::logger log;
log << "ZMQ: Call info" << '\n';
}
omni::giopStream::dumpbuf((unsigned char *)received_call.data(),received_call.size());
}
//
// Extract data from messages
//
unsigned char endian = ((char *)received_endian.data())[0];
string event_name((char *)received_event_name.data(),(size_t)received_event_name.size());
cdrMemoryStream call_info((char *)received_call.data(),(size_t)received_call.size());
call_info.setByteSwapFlag(endian);
ZmqCallInfo_var c_info_var = new ZmqCallInfo;
try
{
(ZmqCallInfo &)c_info_var <<= call_info;
}
catch (...)
{
string st("Received a malformed heartbeat event: ");
st = st + event_name;
print_error_message(st.c_str());
unsigned char *tmp = (unsigned char *)received_call.data();
for (unsigned int loop = 0;loop < received_call.size();loop++)
{
cerr << "Heartbeat event data[" << loop << "] = " << hex << (int)tmp[loop] << dec << endl;
}
return;
}
//
// Call the heartbeat method
//
push_heartbeat_event(event_name);
}
//-------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqEventConsumer::process_event()
//
// description :
// Process execution when a message has been received by the event socket
//
// argument :
// in :
// - received_event_name : The full event name
// - received_endian : The sender endianess
// - received_call : The call informations (oid - method name...)
// - event_data : The event data !
//
//--------------------------------------------------------------------------------------------------------------------
void ZmqEventConsumer::process_event(zmq::message_t &received_event_name,zmq::message_t &received_endian,zmq::message_t &received_call,zmq::message_t &event_data)
{
//cout << "event name message adr = " << (void *)(&received_event_name) << " - size = " << received_event_name.size() << " - ptr = " << (void *)(received_event_name.data()) << endl;
//cout << "endian message adr = " << (void *)(&received_endian) << " - size = " << received_endian.size() << " - ptr = " << (void *)(received_endian.data()) << endl;
//cout << "call info message adr = " << (void *)(&received_call) << " - size = " << received_call.size() << " - ptr = " << (void *)(received_call.data()) << endl;
//cout << "event data message adr = " << (void *)(&event_data) << " - size = " << event_data.size() << " - ptr = " << (void *)(event_data.data()) << endl;
//
// For debug and logging purposes
//
if (omniORB::trace(20))
{
omniORB::logger log;
log << "ZMQ: A event message has been received" << '\n';
}
if (omniORB::trace(30))
{
{
omniORB::logger log;
log << "ZMQ: Event name" << '\n';
}
omni::giopStream::dumpbuf((unsigned char *)received_event_name.data(),received_event_name.size());
{
omniORB::logger log;
log << "ZMQ: Endianess" << '\n';
}
omni::giopStream::dumpbuf((unsigned char *)received_endian.data(),received_endian.size());
{
omniORB::logger log;
log << "ZMQ: Call info" << '\n';
}
omni::giopStream::dumpbuf((unsigned char *)received_call.data(),received_call.size());
{
omniORB::logger log;
log << "ZMQ: Event data" << '\n';
}
omni::giopStream::dumpbuf((unsigned char *)event_data.data(),event_data.size());
}
//
// Extract data from messages
//
const ZmqCallInfo *receiv_call;
unsigned char endian = ((char *)received_endian.data())[0];
string event_name((char *)received_event_name.data(),(size_t)received_event_name.size());
cdrMemoryStream call_info((char *)received_call.data(),(size_t)received_call.size());
call_info.setByteSwapFlag(endian);
ZmqCallInfo_var c_info_var = new ZmqCallInfo;
try
{
(ZmqCallInfo &)c_info_var <<= call_info;
}
catch (...)
{
string st("Received a malformed event call info data for event ");
st = st + event_name;
print_error_message(st.c_str());
unsigned char *tmp = (unsigned char *)received_call.data();
for (unsigned int loop = 0;loop < received_call.size();loop++)
{
cerr << "Event data[" << loop << "] = " << hex << (int)tmp[loop] << dec << endl;
}
return;
}
receiv_call = &c_info_var.in();
//
// Call the event method
//
push_zmq_event(event_name,endian,event_data,receiv_call->call_is_except,receiv_call->ctr);
}
void ZmqEventConsumer::process_event(zmq_msg_t &received_event_name,zmq_msg_t &received_endian,zmq_msg_t &received_call,zmq_msg_t &event_data)
{
//
// For debug and logging purposes
//
if (omniORB::trace(20))
{
omniORB::logger log;
log << "ZMQ: A event message has been received" << '\n';
}
if (omniORB::trace(30))
{
{
omniORB::logger log;
log << "ZMQ: Event name" << '\n';
}
omni::giopStream::dumpbuf((unsigned char *)zmq_msg_data(&received_event_name),zmq_msg_size(&received_event_name));
{
omniORB::logger log;
log << "ZMQ: Endianess" << '\n';
}
omni::giopStream::dumpbuf((unsigned char *)zmq_msg_data(&received_endian),zmq_msg_size(&received_endian));
{
omniORB::logger log;
log << "ZMQ: Call info" << '\n';
}
omni::giopStream::dumpbuf((unsigned char *)zmq_msg_data(&received_call),zmq_msg_size(&received_call));
{
omniORB::logger log;
log << "ZMQ: Event data" << '\n';
}
omni::giopStream::dumpbuf((unsigned char *)zmq_msg_data(&event_data),zmq_msg_size(&event_data));
}
//
// Extract data from messages
//
const ZmqCallInfo *receiv_call;
unsigned char endian = ((char *)zmq_msg_data(&received_endian))[0];
string event_name((char *)zmq_msg_data(&received_event_name),zmq_msg_size(&received_event_name));
cdrMemoryStream call_info((char *)zmq_msg_data(&received_call),zmq_msg_size(&received_call));
call_info.setByteSwapFlag(endian);
ZmqCallInfo_var c_info_var = new ZmqCallInfo;
try
{
(ZmqCallInfo &)c_info_var <<= call_info;
}
catch (...)
{
string st("Received a malformed event call info data for event ");
st = st + event_name;
print_error_message(st.c_str());
unsigned char *tmp = (unsigned char *)zmq_msg_data(&received_call);
for (unsigned int loop = 0;loop < zmq_msg_size(&received_call);loop++)
{
cerr << "Event data[" << loop << "] = " << hex << (int)tmp[loop] << dec << endl;
}
return;
}
receiv_call = &c_info_var.in();
//
// Call the event method
//
zmq::message_t cpp_ev_data;
cpp_ev_data.rebuild(zmq_msg_data(&event_data),zmq_msg_size(&event_data),NULL);
push_zmq_event(event_name,endian,cpp_ev_data,receiv_call->call_is_except,receiv_call->ctr);
}
//-------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqEventConsumer::process_ctrl()
//
// description :
// Process task when something has been received by the control socket
//
// argument :
// in :
// - received_ctrl : The received data
// - poll_list : The ZMQ poll ed item list
// - poll_nb : The item number in previous list
//
// return :
// This method returns true if the calling thread has to exit (because a ZMQ_END command has been received).
// Otherwise, it returns false
//
//--------------------------------------------------------------------------------------------------------------------
bool ZmqEventConsumer::process_ctrl(zmq::message_t &received_ctrl,zmq::pollitem_t *poll_list,int &poll_nb)
{
bool ret = false;
//
// For debug and logging purposes
//
if (omniORB::trace(20))
{
omniORB::logger log;
log << "ZMQ: A control message has been received" << '\n';
}
if (omniORB::trace(30))
{
{
omniORB::logger log;
log << "ZMQ: Control data " << '\n';
}
omni::giopStream::dumpbuf((unsigned char *)received_ctrl.data(),received_ctrl.size());
}
//
// Extract cmd code from messages
//
const char *tmp_ptr = (const char *)received_ctrl.data();
char cmd_code = tmp_ptr[0];
//
// Process each command
//
switch (cmd_code)
{
case ZMQ_END:
{
ret = true;
}
break;
case ZMQ_CONNECT_HEARTBEAT:
{
//
// First extract the endpoint and the event name from received buffer
//
char force_connect = tmp_ptr[1];
const char *endpoint = &(tmp_ptr[2]);
int start = ::strlen(endpoint) + 3;
const char *event_name = &(tmp_ptr[start]);
//
// Connect the heartbeat socket to the new publisher if not already done
//
bool connect_heart = false;
if (connected_heartbeat.empty() == false)
{
if (force_connect == 1)
connect_heart = true;
else
{
vector<string>::iterator pos;
pos = find(connected_heartbeat.begin(),connected_heartbeat.end(),endpoint);
if (pos == connected_heartbeat.end())
connect_heart = true;
}
}
else
connect_heart = true;
if (connect_heart == true)
{
heartbeat_sub_sock->connect(endpoint);
if (force_connect == 0)
connected_heartbeat.push_back(endpoint);
}
//
// Subscribe to the new heartbeat event
//
heartbeat_sub_sock->setsockopt(ZMQ_SUBSCRIBE,event_name,::strlen(event_name));
//
// Most of the time, we have only one TANGO_HOST to take into account and we dont need to execute following code.
// But there are some control system where several TANGO_HOST are defined
//
if (env_var_fqdn_prefix.size() > 1)
{
string base_name(event_name);
multi_tango_host(heartbeat_sub_sock,SUBSCRIBE,base_name);
}
}
break;
case ZMQ_DISCONNECT_HEARTBEAT:
{
//
// Get event name and endpoint name
//
const char *event_name = &(tmp_ptr[1]);
#ifdef ZMQ_HAS_DISCONNECT
const char *endpoint = &(tmp_ptr[1 + ::strlen(event_name) + 1]);
const char *endpoint_event = &(tmp_ptr[1 + ::strlen(event_name) + ::strlen(endpoint) + 2]);
#endif
//
// Unsubscribe this event from the heartbeat socket
//
heartbeat_sub_sock->setsockopt(ZMQ_UNSUBSCRIBE,event_name,::strlen(event_name));
//
// Most of the time, we have only one TANGO_HOST to take into account and we don need to execute following code.
// But there are some control system where several TANGO_HOST are defined
//
if (env_var_fqdn_prefix.size() > 1)
{
string base_name(event_name);
multi_tango_host(heartbeat_sub_sock,UNSUBSCRIBE,base_name);
}
#ifdef ZMQ_HAS_DISCONNECT
//
// Remove the endpoint in the vector of already connected heartbeat and disconnect the socket to this endpoint
//
vector<string>::iterator pos;
string endpoint_str(endpoint);
pos = find(connected_heartbeat.begin(),connected_heartbeat.end(),endpoint_str);
if (pos != connected_heartbeat.end())
connected_heartbeat.erase(pos);
heartbeat_sub_sock->disconnect(endpoint);
//
// Remove the event endpoint from the already connected event and disconnect the event socket
//
pos = find(connected_pub.begin(),connected_pub.end(),string(endpoint_event));
if (pos != connected_pub.end())
{
connected_pub.erase(pos);
event_sub_sock->disconnect(endpoint_event);
}
#endif
}
break;
case ZMQ_CONNECT_EVENT:
{
//
// First extract the endpoint and the event name from received buffer
//
char force_connect = tmp_ptr[1];
const char *endpoint = &(tmp_ptr[2]);
int start = ::strlen(endpoint) + 3;
const char *event_name = &(tmp_ptr[start]);
start = start + ::strlen(event_name) + 1;
Tango::DevLong sub_hwm;
::memcpy(&sub_hwm,&(tmp_ptr[start]),sizeof(Tango::DevLong));
//
// Connect the socket to the publisher
//
bool connect_pub = false;
if (connected_pub.empty() == false)
{
if (force_connect == 1)
connect_pub = true;
else
{
vector<string>::iterator pos;
pos = find(connected_pub.begin(),connected_pub.end(),endpoint);
if (pos == connected_pub.end())
connect_pub = true;
}
}
else
connect_pub = true;
if (connect_pub == true)
{
event_sub_sock->setsockopt(ZMQ_RCVHWM,&sub_hwm,sizeof(sub_hwm));
event_sub_sock->connect(endpoint);
if (force_connect == 0)
connected_pub.push_back(endpoint);
}
//
// Subscribe to the new event
//
event_sub_sock->setsockopt(ZMQ_SUBSCRIBE,event_name,::strlen(event_name));
//
// Most of the time, we have only one TANGO_HOST to take into account and we don't need to execute following code.
// But there are some control system where several TANGO_HOST are defined!
//
if (env_var_fqdn_prefix.size() > 1)
{
string base_name(event_name);
multi_tango_host(event_sub_sock,SUBSCRIBE,base_name);
}
}
break;
case ZMQ_DISCONNECT_EVENT:
{
//
// Get event name
//
const char *event_name = &(tmp_ptr[1]);
string ev_name(event_name);
const char *endpoint = &(tmp_ptr[1 + ::strlen(event_name) + 1]);
string endpoint_str(endpoint);
//
// Check if it is a multicast event
//
bool mcast = false;
map<string,zmq::socket_t *>::iterator pos;
if (event_mcast.empty() != true)
{
pos = event_mcast.find(ev_name);
if (pos != event_mcast.end())
mcast = true;
}
//
// Unsubscribe this event from the socket
//
if (mcast == false)
{
event_sub_sock->setsockopt(ZMQ_UNSUBSCRIBE,event_name,::strlen(event_name));
//
// Most of the time, we have only one TANGO_HOST to take into account and we don need to execute following code.
// But there are some control system where several TANGO_HOST are defined
//
if (env_var_fqdn_prefix.size() > 1)
{
string base_name(event_name);
multi_tango_host(event_sub_sock,UNSUBSCRIBE,base_name);
}
}
else
{
delete pos->second;
event_mcast.erase(pos);
old_poll_nb--;
}
}
break;
case ZMQ_CONNECT_MCAST_EVENT:
{
//
// First extract the endpoint and the event name from received buffer
//
const char *endpoint = &(tmp_ptr[2]);
int start = ::strlen(endpoint) + 3;
const char *event_name = &(tmp_ptr[start]);
start = start + ::strlen(event_name) + 1;
Tango::DevLong sub_hwm,rate,ivl;
::memcpy(&sub_hwm,&(tmp_ptr[start]),sizeof(Tango::DevLong));
start = start + sizeof(Tango::DevLong);
::memcpy(&rate,&(tmp_ptr[start]),sizeof(Tango::DevLong));
start = start + sizeof(Tango::DevLong);
::memcpy(&ivl,&(tmp_ptr[start]),sizeof(Tango::DevLong));
//
// Connect the socket to the publisher
//
bool created_sub = false;
string ev_name(event_name);
map<string,zmq::socket_t *>::iterator pos;
if (event_mcast.empty() == false)
{
pos = event_mcast.find(ev_name);
if (pos != event_mcast.end())
created_sub = true;
}
if (created_sub == false)
{
//
// Check that we are not at the socket high limit
//
if (poll_nb == MAX_SOCKET_SUB)
{
Except::throw_exception((const char *)API_InternalError,
(const char *)"Array to store sockets for zmq poll() call is already full",
(const char *)"ZmqEventConsumer::process_control");
}
//
// Create the socket
//
zmq::socket_t *tmp_sock = new zmq::socket_t(zmq_context,ZMQ_SUB);
//
// Set socket rate, ivl linger and hwm
//
int local_rate = rate;
tmp_sock->setsockopt(ZMQ_RATE,&local_rate,sizeof(local_rate));
int local_ivl = ivl;
tmp_sock->setsockopt(ZMQ_RECOVERY_IVL,&local_ivl,sizeof(local_ivl));
int linger = 0;
tmp_sock->setsockopt(ZMQ_LINGER,&linger,sizeof(linger));
tmp_sock->setsockopt(ZMQ_RCVHWM,&sub_hwm,sizeof(sub_hwm));
//
// Connect the socket
//
tmp_sock->connect(endpoint);
//
// Subscribe to the new event
//
tmp_sock->setsockopt(ZMQ_SUBSCRIBE,event_name,::strlen(event_name));
//
// Store socket in map
//
if (event_mcast.insert(make_pair(ev_name,tmp_sock)).second == false)
{
delete tmp_sock;
print_error_message("Error while inserting pair<event name,mcast socket> in map!");
Except::throw_exception((const char *)API_InternalError,
(const char *)"Error while inserting pair<event name,multicast socket> in map",
(const char *)"ZmqEventConsumer::process_control");
}
//
// Update poll item list
//
poll_list[old_poll_nb].socket = *tmp_sock;
poll_list[old_poll_nb].fd = 0;
poll_list[old_poll_nb].events = ZMQ_POLLIN;
poll_list[old_poll_nb].revents = 0;
old_poll_nb++;
}
}
break;
case ZMQ_DELAY_EVENT:
{
old_poll_nb = poll_nb;
poll_nb = 1;
}
break;
case ZMQ_RELEASE_EVENT:
{
poll_nb = old_poll_nb;
}
break;
default:
print_error_message("ZMQ main thread: Received an unknown command code from control socket!");
break;
}
return ret;
}
//---------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqEventConsumer::multi_tango_host()
//
// description :
// Method to execute a ZMQ socket command (actually only SUBSCRIBE or UNSUBSCRIBE) when several TANGO_HOST is
// used in a control system
//
// argument :
// in :
// - sock : The ZMQ socket
// - cmd : The command to be done on socket
// - event_name: Event name
//
//--------------------------------------------------------------------------------------------------------------------
void ZmqEventConsumer::multi_tango_host(zmq::socket_t *sock,SocketCmd cmd,string &event_name)
{
size_t pos = event_name.find('/',8);
string base_tango_host = event_name.substr(0,pos + 1);
string ev_name = event_name.substr(pos + 1);
for (unsigned int loop = 0;loop < env_var_fqdn_prefix.size();loop++)
{
if (env_var_fqdn_prefix[loop] == base_tango_host)
continue;
else
{
string new_tango_host = env_var_fqdn_prefix[loop] + ev_name;
const char * tmp_ev_name = new_tango_host.c_str();
if (cmd == SUBSCRIBE)
sock->setsockopt(ZMQ_SUBSCRIBE,tmp_ev_name,::strlen(tmp_ev_name));
else
sock->setsockopt(ZMQ_UNSUBSCRIBE,tmp_ev_name,::strlen(tmp_ev_name));
}
}
}
//--------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqEventConsumer::cleanup_EventChannel_map()
//
// description :
// Method to destroy the DeviceProxy objects stored in the EventChannel map.
// It also destroys some allocated objects (to make valgrind happy)
//
//--------------------------------------------------------------------------------------------------------------------
void ZmqEventConsumer::cleanup_EventChannel_map()
{
EvChanIte evt_it;
for (evt_it = channel_map.begin(); evt_it != channel_map.end(); ++evt_it)
{
EventChannelStruct &evt_ch = evt_it->second;
if ((evt_ch.channel_type == ZMQ) && (evt_ch.adm_device_proxy != NULL))
{
AutoTangoMonitor _mon(evt_ch.channel_monitor);
//
// Release the connection to the device server administration device
//
delete evt_ch.adm_device_proxy;
evt_ch.adm_device_proxy = NULL;
}
delete evt_ch.channel_monitor;
}
//
// Delete a Tango monitor in Callback structs
//
EvCbIte cb_it;
for (cb_it = event_callback_map.begin(); cb_it != event_callback_map.end(); ++cb_it)
{
EventCallBackStruct &evt_cb = cb_it->second;
delete evt_cb.callback_monitor;
}
//
// Create and connect the REQ socket used to send message to the ZMQ main thread
//
zmq::message_t reply;
try
{
zmq::socket_t sender(zmq_context,ZMQ_REQ);
sender.connect(CTRL_SOCK_ENDPOINT);
//
// Build message sent to ZMQ main thread. In this case, this is only a command code
//
char buffer[10];
int length = 0;
buffer[length] = ZMQ_END;
length++;
//
// Send command to main ZMQ thread
//
zmq::message_t send_data(length);
::memcpy(send_data.data(),buffer,length);
sender.send(send_data);
sender.recv(&reply);
}
catch(zmq::error_t &) {}
}
//--------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqEventConsumer::connect_event_channel()
//
// description :
// Connect to the event channel. This means connect to the heartbeat event
//
// argument :
// in :
// - channel name : The event channel name (DS admin name)
// - db : Database object
// - reconnect: Flag set to true in case this method is called for event reconnection purpose
// - dd : The DS admin device command returned data (ZmqEventSubscriptionChange command)
//
//--------------------------------------------------------------------------------------------------------------------
void ZmqEventConsumer::connect_event_channel(string &channel_name,TANGO_UNUSED(Database *db),bool reconnect,DeviceData &dd)
{
//
// Extract server command result
//
const DevVarLongStringArray *ev_svr_data;
dd >> ev_svr_data;
//
// Do we have this tango host info in the vector of possible TANGO_HOST. If not get them
//
string prefix = channel_name.substr(0,channel_name.find('/',8) + 1);
bool found = false;
#ifdef HAS_RANGE_BASE_FOR
for (const auto &elem:env_var_fqdn_prefix)
{
if (elem == prefix)
{
found = true;
break;
}
}
#else
vector<string>::iterator ite;
for (ite = env_var_fqdn_prefix.begin();ite != env_var_fqdn_prefix.end();++ite)
{
if (*ite == prefix)
{
found = true;
break;
}
}
#endif
if (found == false && db != NULL)
{
get_cs_tango_host(db);
}
//
// If the server has returned several possible ZMQ endpoints (because several NIC boards on server host), check which
// one is correct
//
size_t nb_endpoint = ev_svr_data->svalue.length();
nb_endpoint = nb_endpoint >> 1;
size_t valid_endpoint = 0;
if (nb_endpoint != 1)
{
for (valid_endpoint = 0;valid_endpoint < nb_endpoint;valid_endpoint++)
{
string endpoint(ev_svr_data->svalue[valid_endpoint << 1]);
if (check_zmq_endpoint(endpoint) == true)
break;
}
if (valid_endpoint == nb_endpoint)
{
stringstream o;
o << "Failed to create connection to event channel!\n";
o << "Impossible to create a network connection to any of the event endpoints returned by server";
Except::throw_exception(API_ZmqFailed,o.str(),"ZmqEventConsumer::connect_event_channel");
}
}
//
// Create and connect the REQ socket used to send message to the ZMQ main thread
//
zmq::message_t reply;
try
{
zmq::socket_t sender(zmq_context,ZMQ_REQ);
//
// In case this thread runs before the main ZMQ thread, it is possible to call connect before the main ZMQ thread has
// binded its socket. In such a case, error code is set to ECONNREFUSED.
// If this happens, give the main ZMQ thread a chance to run and retry the connect call
// I have tried with a yield call but it still failed in some cases (when running the DS with a file as database for
// instance). Replace the yield with a 10 mS sleep !!!
//
try
{
sender.connect(CTRL_SOCK_ENDPOINT);
}
catch (zmq::error_t &e)
{
if (e.num() == ECONNREFUSED)
{
#ifndef _TG_WINDOWS_
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 10000000;
nanosleep(&ts,NULL);
#else
Sleep(10);
#endif
sender.connect(CTRL_SOCK_ENDPOINT);
}
else
throw;
}
//
// Build message sent to ZMQ main thread
// In this case, this is the command code, the publisher endpoint and the event name
//
char buffer[1024];
int length = 0;
buffer[length] = ZMQ_CONNECT_HEARTBEAT;
length++;
#ifdef ZMQ_HAS_DISCONNECT
buffer[length] = 0;
#else
if (reconnect == true)
buffer[length] = 1;
else
buffer[length] = 0;
#endif
length++;
::strcpy(&(buffer[length]),ev_svr_data->svalue[valid_endpoint].in());
length = length + ::strlen(ev_svr_data->svalue[valid_endpoint].in()) + 1;
string sub(channel_name);
sub = sub + '.' + HEARTBEAT_EVENT_NAME;
::strcpy(&(buffer[length]),sub.c_str());
length = length + sub.size() + 1;
//
// Send command to main ZMQ thread
//
zmq::message_t send_data(length);
::memcpy(send_data.data(),buffer,length);
sender.send(send_data);
sender.recv(&reply);
}
catch(zmq::error_t &e)
{
stringstream o;
o << "Failed to create connection to event channel!\n";
o << "Error while communicating with the ZMQ main thread\n";
o << "ZMQ error code = " << e.num() << "\n";
o << "ZMQ message: " << e.what() << ends;
Except::throw_exception(API_ZmqFailed,o.str(),"ZmqEventConsumer::connect_event_channel");
}
//
// Any error during ZMQ main thread socket operations?
//
if (reply.size() != 2)
{
char err_mess[512];
::memcpy(err_mess,reply.data(),reply.size());
err_mess[reply.size()] = '\0';
stringstream o;
o << "Failed to create connection to event channel!\n";
o << "Error while trying to connect or subscribe the heartbeat ZMQ socket to the new publisher\n";
o << "ZMQ message: " << err_mess << ends;
Except::throw_exception(API_ZmqFailed,o.str(),"ZmqEventConsumer::connect_event_channel");
}
//
// Init (or create) EventChannelStruct
//
EvChanIte evt_it = channel_map.end();
if (reconnect == true)
{
evt_it = channel_map.find(channel_name);
EventChannelStruct &evt_ch = evt_it->second;
evt_ch.last_heartbeat = time(NULL);
evt_ch.heartbeat_skipped = false;
evt_ch.event_system_failed = false;
evt_ch.endpoint = ev_svr_data->svalue[valid_endpoint].in();
evt_ch.valid_endpoint = valid_endpoint;
}
else
{
EventChannelStruct new_event_channel_struct;
new_event_channel_struct.last_heartbeat = time(NULL);
new_event_channel_struct.heartbeat_skipped = false;
new_event_channel_struct.adm_device_proxy = NULL;
// create a channel monitor
new_event_channel_struct.channel_monitor = new TangoMonitor(channel_name.c_str());
// set the timeout for the channel monitor to 1000ms not to block the event consumer for to long.
new_event_channel_struct.channel_monitor->timeout(1000);
new_event_channel_struct.event_system_failed = false;
set_channel_type(new_event_channel_struct);
new_event_channel_struct.endpoint = ev_svr_data->svalue[valid_endpoint].in();
new_event_channel_struct.valid_endpoint = valid_endpoint;
channel_map[channel_name] = new_event_channel_struct;
}
}
//--------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqEventConsumer::disconnect_event_channel()
//
// description :
// Disconnect to the event channel. This means that the process should not receive the heartbeat event for this
// channel. It will be filtered out by ZMQ
//
// argument :
// in :
// - channel name : The event channel name (DS admin name)
// - endpoint : The ZMQ endpoint for the heartbeat publisher socket
// - endpoint_event : The ZMQ endpoint for the event publisher socket
//
//--------------------------------------------------------------------------------------------------------------------
void ZmqEventConsumer::disconnect_event_channel(string &channel_name,string &endpoint,string &endpoint_event)
{
string unsub(channel_name);
unsub = unsub + '.' + HEARTBEAT_EVENT_NAME;
//
// Create and connect the REQ socket used to send message to the ZMQ main thread
//
zmq::message_t reply;
try
{
zmq::socket_t sender(zmq_context,ZMQ_REQ);
sender.connect(CTRL_SOCK_ENDPOINT);
//
// Build message sent to ZMQ main thread
// In this case, this is the command code, the publisher endpoint and the event name
//
char buffer[1024];
int length = 0;
buffer[length] = ZMQ_DISCONNECT_HEARTBEAT;
length++;
::strcpy(&(buffer[length]),unsub.c_str());
length = length + unsub.size() + 1;
::strcpy(&(buffer[length]),endpoint.c_str());
length = length + endpoint.size() + 1;
::strcpy(&(buffer[length]),endpoint_event.c_str());
length = length + endpoint_event.size() + 1;
//
// Send command to main ZMQ thread
//
zmq::message_t send_data(length);
::memcpy(send_data.data(),buffer,length);
sender.send(send_data);
sender.recv(&reply);
}
catch (zmq::error_t &e)
{
TangoSys_OMemStream o;
o << "Failed to disconnect from the event channel!\n";
o << "Error while communicating with the ZMQ main thread\n";
o << "ZMQ message: " << e.what() << ends;
Except::throw_exception((const char *)API_ZmqFailed,
o.str(),
(const char *)"ZmqEventConsumer::disconnect_event_channel");
}
//
// In case of error returned by the main ZMQ thread
//
if (reply.size() != 2)
{
char err_mess[512];
::memcpy(err_mess,reply.data(),reply.size());
err_mess[reply.size()] = '\0';
TangoSys_OMemStream o;
o << "Failed to disconnect from event channel!\n";
o << "Error while trying to unsubscribe the heartbeat ZMQ socket from the channel heartbeat publisher\n";
o << "ZMQ message: " << err_mess << ends;
Except::throw_exception((const char *)API_ZmqFailed,
o.str(),
(const char *)"ZmqEventConsumer::disconnect_event_channel");
}
}
//--------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqEventConsumer::disconnect_event()
//
// description :
// Disconnect to the event. This means that the process should not receive the event any more
// It will be filtered out by ZMQ
//
// argument :
// in :
// - event_name : The event name
//
//--------------------------------------------------------------------------------------------------------------------
void ZmqEventConsumer::disconnect_event(string &event_name,string &endpoint)
{
//
// Create and connect the REQ socket used to send message to the ZMQ main thread
//
zmq::message_t reply;
try
{
zmq::socket_t sender(zmq_context,ZMQ_REQ);
sender.connect(CTRL_SOCK_ENDPOINT);
//
// Build message sent to ZMQ main thread
// In this case, this is the command code, the publisher endpoint and the event name
//
char buffer[1024];
int length = 0;
buffer[length] = ZMQ_DISCONNECT_EVENT;
length++;
::strcpy(&(buffer[length]),event_name.c_str());
length = length + event_name.size() + 1;
::strcpy(&(buffer[length]),endpoint.c_str());
length = length + endpoint.size() + 1;
//
// Send command to main ZMQ thread
//
zmq::message_t send_data(length);
::memcpy(send_data.data(),buffer,length);
sender.send(send_data);
sender.recv(&reply);
}
catch (zmq::error_t &e)
{
TangoSys_OMemStream o;
o << "Failed to disconnect from event!\n";
o << "Error while communicating with the ZMQ main thread\n";
o << "ZMQ message: " << e.what() << ends;
Except::throw_exception((const char *)API_ZmqFailed,
o.str(),
(const char *)"ZmqEventConsumer::disconnect_event");
}
//
// In case of error returned by the main ZMQ thread
//
if (reply.size() != 2)
{
char err_mess[512];
::memcpy(err_mess,reply.data(),reply.size());
err_mess[reply.size()] = '\0';
TangoSys_OMemStream o;
o << "Failed to disconnect from event!\n";
o << "Error while trying to unsubscribe the heartbeat ZMQ socket from the channel heartbeat publisher\n";
o << "ZMQ message: " << err_mess << ends;
Except::throw_exception((const char *)API_ZmqFailed,
o.str(),
(const char *)"ZmqEventConsumer::disconnect_event");
}
}
//--------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqEventConsumer::connect_event_system()
//
// description :
// Connect to the real event (change, archive,...)
//
// argument :
// in :
// - device_name : The device fqdn (lower case)
// - obj_name : The attribute/pipe name
// - event_name : The event name
// - filters : The event filters given by the user
// - evt_it : Iterator pointing to the event channel entry in channel_map map
// - new_event_callback : Structure used for the event callback entry in the event_callback_map
// - dd : The data returned by the DS admin device xxxSubscriptionChange command
// - valid_end : The valid endpoint in the list of endpoint returned by ZMQEventSubscriptionChange command
//
//--------------------------------------------------------------------------------------------------------------------
void ZmqEventConsumer::connect_event_system(string &device_name,string &obj_name,string &event_name,TANGO_UNUSED(const vector<string> &filters),
TANGO_UNUSED(EvChanIte &eve_it),TANGO_UNUSED(EventCallBackStruct &new_event_callback),
DeviceData &dd,size_t valid_end)
{
//
// Build full event name
// Don't forget case of device in a DS using file as database
//
string full_event_name;
string::size_type pos;
bool inter_event = false;
if (event_name == EventName[INTERFACE_CHANGE_EVENT])
inter_event = true;
if ((pos = device_name.find(MODIFIER_DBASE_NO)) != string::npos)
{
full_event_name = device_name;
if (inter_event == false)
{
string tmp = '/' + obj_name;
full_event_name.insert(pos,tmp);
}
full_event_name = full_event_name + '.' + event_name;
}
else
{
if (inter_event == true)
full_event_name = device_name + '.' + event_name;
else
full_event_name = device_name + '/' + obj_name + '.' + event_name;
}
//
// Extract server command result
//
const DevVarLongStringArray *ev_svr_data;
dd >> ev_svr_data;
//
// Create and connect the REQ socket used to send message to the ZMQ main thread
//
zmq::message_t reply;
try
{
zmq::socket_t sender(zmq_context,ZMQ_REQ);
sender.connect(CTRL_SOCK_ENDPOINT);
//
// If the transport is multicast, add main IP interface address in endpoint
//
bool mcast_transport = false;
ApiUtil *au = ApiUtil::instance();
string endpoint(ev_svr_data->svalue[(valid_end << 1) + 1].in());
if (endpoint.find(MCAST_PROT) != string::npos)
{
mcast_transport = true;
vector<string> adrs;
au->get_ip_from_if(adrs);
for (unsigned int i = 0;i < adrs.size();++i)
{
if (adrs[i].find("127.") == 0)
continue;
adrs[i] = adrs[i] + ';';
string::size_type pos = endpoint.find('/');
pos = pos + 2;
endpoint.insert(pos,adrs[i]);
break;
}
}
//
// Build message sent to ZMQ main thread
// In this case, this is the command code, the publisher endpoint, the event name and the sub hwm
//
char buffer[1024];
int length = 0;
if (mcast_transport == true)
buffer[length] = ZMQ_CONNECT_MCAST_EVENT;
else
buffer[length] = ZMQ_CONNECT_EVENT;
length++;
#ifdef ZMQ_HAS_DISCONNECT
buffer[length] = 0;
#else
if (filters.size() == 1 && filters[0] == "reconnect")
buffer[length] = 1;
else
buffer[length] = 0;
#endif
length++;
::strcpy(&(buffer[length]),endpoint.c_str());
length = length + endpoint.size() + 1;
::strcpy(&(buffer[length]),full_event_name.c_str());
length = length + full_event_name.size() + 1;
DevLong user_hwm = au->get_user_sub_hwm();
if (user_hwm != -1)
::memcpy(&(buffer[length]),&(user_hwm),sizeof(Tango::DevLong));
else
::memcpy(&(buffer[length]),&(ev_svr_data->lvalue[2]),sizeof(Tango::DevLong));
length = length + sizeof(Tango::DevLong);
//
// In case of multicasting, add rate and ivl parameters
//
if (mcast_transport == true)
{
::memcpy(&(buffer[length]),&(ev_svr_data->lvalue[3]),sizeof(Tango::DevLong));
length = length + sizeof(Tango::DevLong);
::memcpy(&(buffer[length]),&(ev_svr_data->lvalue[4]),sizeof(Tango::DevLong));
length = length + sizeof(Tango::DevLong);
}
//
// Send command to main ZMQ thread
//
zmq::message_t send_data(length);
::memcpy(send_data.data(),buffer,length);
sender.send(send_data);
sender.recv(&reply);
}
catch(zmq::error_t &e)
{
stringstream o;
o << "Failed to create connection to event!\n";
o << "Error while communicating with the ZMQ main thread\n";
o << "ZMQ message: " << e.what() << ends;
Except::throw_exception(API_ZmqFailed,o.str(),"ZmqEventConsumer::connect_event_system");
}
//
// Any error during ZMQ main thread socket operations?
//
if (reply.size() != 2)
{
char err_mess[512];
::memcpy(err_mess,reply.data(),reply.size());
err_mess[reply.size()] = '\0';
stringstream o;
o << "Failed to create connection to event!\n";
o << "Error while trying to connect or subscribe the event ZMQ socket to the new publisher\n";
o << "ZMQ message: " << err_mess << ends;
Except::throw_exception(API_ZmqFailed,o.str(),"ZmqEventConsumer::connect_event_system");
}
}
//--------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqEventConsumer::push_heartbeat_event()
//
// description :
// Method called when the heartbeat event is received. This method retrieve the channel entry in the channel_map
// and update the last heartbeat date.
//
// argument :
// in :
// - ev_name : The fully qualifed event name
//
//--------------------------------------------------------------------------------------------------------------------
void ZmqEventConsumer::push_heartbeat_event(string &ev_name)
{
//
// Remove ".heartbeat" at the end of event name
//
string::size_type pos = ev_name.find(".heartbeat");
if (pos == string::npos)
{
return;
}
ev_name.erase(pos);
//
// Only reading from the maps
//
map_modification_lock.readerIn();
std::map<std::string,EventChannelStruct>::iterator ipos;
ipos = channel_map.find(ev_name);
if (ipos != channel_map.end())
{
EventChannelStruct &evt_ch = ipos->second;
try
{
AutoTangoMonitor _mon(evt_ch.channel_monitor);
evt_ch.last_heartbeat = time(NULL);
}
catch (...)
{
string st("Tango::ZmqEventConsumer::push_heartbeat_event() timeout on channel monitor of ");
st = st + ipos->first;
print_error_message(st.c_str());
}
}
else
{
unsigned int loop = 0;
if (env_var_fqdn_prefix.size() > 1)
{
size_t pos = ev_name.find('/',8);
string base_tango_host = ev_name.substr(0,pos + 1);
string canon_ev_name = ev_name.substr(pos + 1);
for (loop = 0;loop < env_var_fqdn_prefix.size();loop++)
{
if (env_var_fqdn_prefix[loop] == base_tango_host)
continue;
else
{
string new_tango_host = env_var_fqdn_prefix[loop] + canon_ev_name;
ipos = channel_map.find(new_tango_host);
if (ipos != channel_map.end())
{
EventChannelStruct &evt_ch = ipos->second;
try
{
AutoTangoMonitor _mon(evt_ch.channel_monitor);
evt_ch.last_heartbeat = time(NULL);
}
catch (...)
{
string st("Tango::ZmqEventConsumer::push_heartbeat_event() timeout on channel monitor of ");
st = st + ipos->first;
print_error_message(st.c_str());
}
break;
}
}
}
}
if (loop == env_var_fqdn_prefix.size())
{
string st("No entry in channel map for heartbeat ");
st = st + ev_name;
print_error_message(st.c_str());
}
}
map_modification_lock.readerOut();
}
//--------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqEventConsumer::push_zmq_event()
//
// description :
// Method called when the event is received. This method retrieve the channel entry in the channel_map
// and update the last heartbeat date.
//
// argument :
// in :
// - ev_name : The fully qualifed event name
// - endian : The sender host endianess
// - event_data : The event data still in a ZMQ message
// - error : Flag set to true if the event data is an error stack
// - ctr : Event counter as received from server
//
//--------------------------------------------------------------------------------------------------------------------
void ZmqEventConsumer::push_zmq_event(string &ev_name,unsigned char endian,zmq::message_t &event_data,bool error,const DevULong &ds_ctr)
{
map_modification_lock.readerIn();
bool map_lock = true;
// cout << "Lib: Received event for " << ev_name << endl;
// for (const auto &elem : event_callback_map)
// printf("Key in event_callback_map = %s\n",elem.first.c_str());
// for (const auto &elem : channel_map)
// printf("Key in channel_map = %s\n",elem.first.c_str());
//
// Search for entry within the event_callback map using the event name received in the event
//
map<std::string,EventCallBackStruct>::iterator ipos;
size_t loop;
bool no_db_dev = false;
bool first_search_succeed = false;
size_t pos = ev_name.find('/',8);
string base_tango_host = ev_name.substr(0,pos + 1);
string canon_ev_name = ev_name.substr(pos + 1);
if (ev_name.find(MODIFIER_DBASE_NO) != string::npos)
no_db_dev = true;
for (loop = 0;loop < env_var_fqdn_prefix.size() + 1;loop++)
{
//
// Test different fully qualified event name depending on different TANGO_HOST defined for the control system
//
string new_tango_host;
if (loop == 0 || no_db_dev == true)
new_tango_host = ev_name;
else
new_tango_host = env_var_fqdn_prefix[loop - 1] + canon_ev_name;
ipos = event_callback_map.find(new_tango_host);
if (ipos != event_callback_map.end())
{
if (loop == 0)
first_search_succeed = true;
const AttributeValue *attr_value = NULL;
const AttributeValue_3 *attr_value_3 = NULL;
const ZmqAttributeValue_4 *z_attr_value_4 = NULL;
const ZmqAttributeValue_5 *z_attr_value_5 = NULL;
const AttributeConfig_2 *attr_conf_2 = NULL;
const AttributeConfig_3 *attr_conf_3 = NULL;
const AttributeConfig_5 *attr_conf_5 = NULL;
AttDataReady *att_ready = NULL;
DevIntrChange *dev_intr_change = NULL;
const DevErrorList *err_ptr;
DevErrorList errors;
AttributeInfoEx *attr_info_ex = NULL;
bool ev_attr_conf = false;
bool ev_attr_ready = false;
bool ev_dev_intr = false;
bool pipe_event = false;
EventCallBackStruct &evt_cb = ipos->second;
//
// Miss some events?
// Due to LIBZMQ Bug 283, the first event after a process startup is sent two times
// with the same ctr value. Do not call the user callback for the second times.
//
bool err_missed_event = false;
if (ds_ctr != 1 && evt_cb.ctr == 0)
evt_cb.ctr = ds_ctr - 1;
DevLong missed_event = ds_ctr - evt_cb.ctr;
if (missed_event < 0)
{
missed_event = (UINT_MAX + missed_event) + 1;
}
if (missed_event >= 2)
{
err_missed_event = true;
evt_cb.discarded_event = false;
}
else if (missed_event == 0)
{
if (evt_cb.discarded_event == false)
{
evt_cb.discarded_event = true;
map_modification_lock.readerOut();
return;
}
else
evt_cb.discarded_event = false;
}
else
evt_cb.discarded_event = false;
evt_cb.ctr = ds_ctr;
//
// Get which type of event data has been received (from the event type)
//
string::size_type pos = ev_name.rfind('.');
string event_name = ev_name.substr(pos + 1);
string::size_type pos1 = event_name.find(EVENT_COMPAT);
if (pos1 != string::npos)
event_name.erase(0,EVENT_COMPAT_IDL5_SIZE);
//
// If the client TANGO_HOST is one alias, replace in the event name the host name by the alias
//
string full_att_name;
if (evt_cb.alias_used == true)
{
pos = evt_cb.fully_qualified_event_name.rfind('.');
full_att_name = evt_cb.fully_qualified_event_name.substr(0,pos);
string::size_type pos = full_att_name.find(':',8);
string host = full_att_name.substr(8,pos - 8);
map<string,string>::iterator ite = alias_map.find(host);
if (ite != alias_map.end())
full_att_name.replace(8,pos - 8,ite->second);
}
else
{
if (first_search_succeed == true)
full_att_name = ev_name.substr(0,pos);
else
{
pos = evt_cb.fully_qualified_event_name.rfind('.');
full_att_name = evt_cb.fully_qualified_event_name.substr(0,pos);
}
}
pos = full_att_name.rfind('/');
string att_name = full_att_name.substr(pos + 1);
UserDataEventType data_type;
if (event_name.find(CONF_TYPE_EVENT) != string::npos)
data_type = ATT_CONF;
else if (event_name == DATA_READY_TYPE_EVENT)
data_type = ATT_READY;
else if (event_name == EventName[INTERFACE_CHANGE_EVENT])
data_type = DEV_INTR;
else if (event_name == EventName[PIPE_EVENT])
data_type = PIPE;
else
data_type = ATT_VALUE;
//
// Unmarshal the event data
//
long vers = 0;
DeviceAttribute *dev_attr = NULL;
DevicePipe *dev_pipe = NULL;
bool no_unmarshalling = false;
if (evt_cb.fwd_att == true && data_type != ATT_CONF && error == false)
{
no_unmarshalling = true;
}
else
{
//
// For 64 bits data (double, long64 and ulong64), omniORB unmarshalling
// methods required that the 64 bits data are aligned on a 8 bytes memory address.
// ZMQ returned memory which is sometimes aligned on a 8 bytes boundary but
// not always (seems to depend on the host architecture)
// The attribute data transfert starts with the union discriminator
// (4 bytes), the elt nb (4 bytes) and the element themselves.
// This means 8 bytes before the real data.
// There is a trick here.
// The buffer is always transferred with an extra 4 bytes added at the beginning
// If the alignememnt is not correct (buffer aligned on a 8 bytes boundary
// and 64 bits data type), shift the whole buffer by 4 bytes erasing the
// additional 4 bytes sent.
//
// Note: The buffer is not correctly aligned if it is returned on a
// 8 bytes boundary because we have the 4 extra bytes + 8 bytes for
// union discriminator + elt nb. This means 64 bits data not on a
// 8 bytes boundary
//
char *data_ptr = (char *)event_data.data();
size_t data_size = (size_t)event_data.size();
bool shift_zmq420 = false;
int shift_mem = (unsigned long)data_ptr & 0x3;
if (shift_mem != 0)
{
char *src = data_ptr + 4;
size_t size_to_move = data_size - 4;
if (data_type == PIPE)
{
src = src + 4;
size_to_move = size_to_move - 4;
}
char *dest = src - shift_mem;
if (((unsigned long)dest & 0x7) == 4)
dest = dest - 4;
memmove((void *)dest,(void *)src,size_to_move);
shift_zmq420 = true;
data_ptr = dest;
}
bool data64 = false;
if (data_type == PIPE)
data64 = true;
else if (data_type == ATT_VALUE && error == false)
{
int disc = shift_zmq420 == true ? ((int *)data_ptr)[0] : ((int *)data_ptr)[1];
if (endian == 0)
{
char first_byte = disc & 0xFF;
char second_byte = (disc & 0xFF00) >> 8;
char third_byte = (disc & 0xFF0000) >> 16;
char forth_byte = (disc & 0xFF000000) >> 24;
disc = 0;
disc = forth_byte + (third_byte << 8) + (second_byte << 16) + (first_byte << 24);
}
if (disc == ATT_DOUBLE || disc == ATT_LONG64 || disc == ATT_ULONG64)
data64 = true;
}
bool buffer_aligned64 = false;
if (data64 == true)
{
if (((unsigned long)data_ptr & 0x7) == 0)
buffer_aligned64 = true;
}
//
// Shift buffer if required
//
if (data_type == PIPE && data64 == true && buffer_aligned64 == false)
{
if (omniORB::trace(30))
{
omniORB::logger log;
log << "ZMQ: Pipe event -> Shifting received buffer to be aligned on a 8 bytes boundary" << '\n';
}
char *src = data_ptr + 8;
char *dest = data_ptr + 4;
memmove((void *)dest,(void *)src,data_size - 8);
data_ptr = data_ptr + 4;
data_size = data_size - 4;
}
else if (data_type != PIPE && data64 == true && buffer_aligned64 == true && shift_zmq420 == false)
{
if (omniORB::trace(30))
{
omniORB::logger log;
log << "ZMQ: Classical event -> Shifting received buffer to be aligned on a 8 bytes boundary" << '\n';
}
char *src = data_ptr + 4;
char *dest = data_ptr;
memmove((void *)dest,(void *)src,data_size - 4);
data_size = data_size - 4;
}
else
{
if (data_type == PIPE)
{
if (shift_zmq420 == false)
data_ptr = data_ptr + (sizeof(CORBA::Long) << 1);
data_size = data_size - (sizeof(CORBA::Long) << 1);
}
else
{
if (shift_zmq420 == false)
data_ptr = data_ptr + sizeof(CORBA::Long);
data_size = data_size - sizeof(CORBA::Long);
}
}
TangoCdrMemoryStream event_data_cdr(data_ptr,data_size);
event_data_cdr.setByteSwapFlag(endian);
//
// Unmarshall the data
//
if (error == true)
{
switch (data_type)
{
case ATT_CONF:
ev_attr_conf = true;
break;
case ATT_READY:
ev_attr_ready = true;
break;
case DEV_INTR:
ev_dev_intr = true;
break;
case PIPE:
pipe_event = true;
break;
default:
break;
}
try
{
(DevErrorList &)del <<= event_data_cdr;
err_ptr = &del.in();
errors = *err_ptr;
}
catch(...)
{
TangoSys_OMemStream o;
o << "Received malformed data for event ";
o << ev_name << ends;
errors.length(1);
errors[0].reason = API_WrongEventData;
errors[0].origin = "ZmqEventConsumer::push_zmq_event()";
errors[0].desc = CORBA::string_dup(o.str().c_str());
errors[0].severity = ERR;
}
}
else
{
switch (data_type)
{
case ATT_CONF:
if (evt_cb.device_idl > 4)
{
//
// Event if the device sending the event is IDL 5
//
try
{
ev_attr_conf = true;
(AttributeConfig_5 &)ac5 <<= event_data_cdr;
attr_conf_5 = &ac5.in();
vers = 5;
attr_info_ex = new AttributeInfoEx();
*attr_info_ex = const_cast<AttributeConfig_5 *>(attr_conf_5);
}
catch(...)
{
TangoSys_OMemStream o;
o << "Received malformed data for event ";
o << ev_name << ends;
errors.length(1);
errors[0].reason = API_WrongEventData;
errors[0].origin = "ZmqEventConsumer::push_zmq_event()";
errors[0].desc = CORBA::string_dup(o.str().c_str());
errors[0].severity = ERR;
}
}
else if (evt_cb.device_idl > 2)
{
try
{
ev_attr_conf = true;
(AttributeConfig_3 &)ac3 <<= event_data_cdr;
attr_conf_3 = &ac3.in();
vers = 3;
attr_info_ex = new AttributeInfoEx();
*attr_info_ex = const_cast<AttributeConfig_3 *>(attr_conf_3);
}
catch(...)
{
TangoSys_OMemStream o;
o << "Received malformed data for event ";
o << ev_name << ends;
errors.length(1);
errors[0].reason = API_WrongEventData;
errors[0].origin = "ZmqEventConsumer::push_zmq_event()";
errors[0].desc = CORBA::string_dup(o.str().c_str());
errors[0].severity = ERR;
}
}
else if (evt_cb.device_idl == 2)
{
ev_attr_conf = true;
(AttributeConfig_2 &)ac2 <<= event_data_cdr;
attr_conf_2 = &ac2.in();
vers = 2;
attr_info_ex = new AttributeInfoEx();
*attr_info_ex = const_cast<AttributeConfig_2 *>(attr_conf_2);
}
break;
case ATT_READY:
try
{
ev_attr_ready = true;
(AttDataReady &)adr <<= event_data_cdr;
att_ready = &adr.inout();
att_ready->name = full_att_name.c_str();
}
catch(...)
{
TangoSys_OMemStream o;
o << "Received malformed data for event ";
o << ev_name << ends;
errors.length(1);
errors[0].reason = API_WrongEventData;
errors[0].origin = "ZmqEventConsumer::push_zmq_event()";
errors[0].desc = CORBA::string_dup(o.str().c_str());
errors[0].severity = ERR;
}
break;
case DEV_INTR:
try
{
ev_dev_intr = true;
(DevIntrChange &)dic <<= event_data_cdr;
dev_intr_change = &dic.inout();
}
catch(...)
{
TangoSys_OMemStream o;
o << "Received malformed data for event ";
o << ev_name << ends;
errors.length(1);
errors[0].reason = API_WrongEventData;
errors[0].origin = "ZmqEventConsumer::push_zmq_event()";
errors[0].desc = CORBA::string_dup(o.str().c_str());
errors[0].severity = ERR;
}
break;
case ATT_VALUE:
if (evt_cb.device_idl >= 5)
{
event_data_cdr.set_un_marshal_type(TangoCdrMemoryStream::UN_ATT);
try
{
vers = 5;
zav5.operator<<=(event_data_cdr);
z_attr_value_5 = &zav5;
dev_attr = new (DeviceAttribute);
attr_to_device(z_attr_value_5,dev_attr);
//
// Update name in DeviceAttribute in case it is not coherent with name received in first ZMQ message part.
// This happens in case of forwarded attribute but also in case of DS started with file as database
//
string::size_type pos = att_name.find(MODIFIER_DBASE_NO);
string a_name;
if (pos != string::npos)
a_name = att_name.substr(0,pos);
else
a_name = att_name;
if (a_name != dev_attr->get_name())
dev_attr->set_name(a_name);
}
catch(...)
{
TangoSys_OMemStream o;
o << "Received malformed data for event ";
o << ev_name << ends;
errors.length(1);
errors[0].reason = API_WrongEventData;
errors[0].origin = "ZmqEventConsumer::push_zmq_event()";
errors[0].desc = CORBA::string_dup(o.str().c_str());
errors[0].severity = ERR;
}
}
else if (evt_cb.device_idl == 4)
{
event_data_cdr.set_un_marshal_type(TangoCdrMemoryStream::UN_ATT);
try
{
vers = 4;
zav4.operator<<=(event_data_cdr);
z_attr_value_4 = &zav4;
dev_attr = new (DeviceAttribute);
attr_to_device(z_attr_value_4,dev_attr);
//
// Update name in DeviceAttribute in case it is not coherent with name received in first ZMQ message part.
// This happens in case of forwarded attribute but also in case of DS started with file as database
//
string::size_type pos = att_name.find(MODIFIER_DBASE_NO);
string a_name;
if (pos != string::npos)
a_name = att_name.substr(0,pos);
else
a_name = att_name;
if (a_name != dev_attr->get_name())
dev_attr->set_name(a_name);
}
catch(...)
{
TangoSys_OMemStream o;
o << "Received malformed data for event ";
o << ev_name << ends;
errors.length(1);
errors[0].reason = API_WrongEventData;
errors[0].origin = "ZmqEventConsumer::push_zmq_event()";
errors[0].desc = CORBA::string_dup(o.str().c_str());
errors[0].severity = ERR;
}
}
else if (evt_cb.device_idl == 3)
{
event_data_cdr.set_un_marshal_type(TangoCdrMemoryStream::UN_ATT);
try
{
vers = 3;
(AttributeValue_3 &)av3 <<= event_data_cdr;
attr_value_3 = &av3.in();
dev_attr = new (DeviceAttribute);
attr_to_device(attr_value,attr_value_3,vers,dev_attr);
}
catch(...)
{
TangoSys_OMemStream o;
o << "Received malformed data for event (AttributeValue_3 -> Device_3Impl....) ";
o << ev_name << ends;
errors.length(1);
errors[0].reason = API_WrongEventData;
errors[0].origin = "ZmqEventConsumer::push_zmq_event()";
errors[0].desc = CORBA::string_dup(o.str().c_str());
errors[0].severity = ERR;
}
}
else if (evt_cb.device_idl < 3)
{
try
{
vers = 2;
(AttributeValue &)av <<= event_data_cdr;
attr_value = &av.in();
dev_attr = new (DeviceAttribute);
attr_to_device(attr_value,attr_value_3,vers,dev_attr);
}
catch(...)
{
TangoSys_OMemStream o;
o << "Received malformed data for event (AttributeValue -> Device_2Impl....) ";
o << ev_name << ends;
errors.length(1);
errors[0].reason = API_WrongEventData;
errors[0].origin = "ZmqEventConsumer::push_zmq_event()";
errors[0].desc = CORBA::string_dup(o.str().c_str());
errors[0].severity = ERR;
}
}
break;
case PIPE:
event_data_cdr.set_un_marshal_type(TangoCdrMemoryStream::UN_PIPE);
try
{
pipe_event = true;
zdpd.operator<<=(event_data_cdr);
string pipe_name = zdpd.name.in();
string root_blob_name = zdpd.data_blob.name.in();
dev_pipe = new DevicePipe(pipe_name,root_blob_name);
dev_pipe->set_time(zdpd.time);
CORBA::ULong max,len;
max = zdpd.data_blob.blob_data.maximum();
len = zdpd.data_blob.blob_data.length();
DevPipeDataElt *buf = zdpd.data_blob.blob_data.get_buffer((CORBA::Boolean)true);
DevVarPipeDataEltArray *dvpdea = new DevVarPipeDataEltArray(max,len,buf,true);
dev_pipe->get_root_blob().set_extract_data(dvpdea);
dev_pipe->get_root_blob().set_extract_delete(true);
}
catch(...)
{
TangoSys_OMemStream o;
o << "Received malformed data for event ";
o << ev_name << ends;
errors.length(1);
errors[0].reason = API_WrongEventData;
errors[0].origin = "ZmqEventConsumer::push_zmq_event()";
errors[0].desc = CORBA::string_dup(o.str().c_str());
errors[0].severity = ERR;
}
break;
}
}
}
FwdEventData *missed_event_data = NULL;
FwdAttrConfEventData *missed_conf_event_data = NULL;
DataReadyEventData *missed_ready_event_data = NULL;
DevIntrChangeEventData *missed_dev_intr_event_data = NULL;
PipeEventData *missed_dev_pipe_data = NULL;
try
{
AutoTangoMonitor _mon(evt_cb.callback_monitor);
//
// In case we have missed some event, prepare structure to send to callback to inform user of this bad behavior
//
if (err_missed_event == true)
{
DevErrorList missed_errors;
missed_errors.length(1);
missed_errors[0].reason = API_MissedEvents;
missed_errors[0].origin = "ZmqEventConsumer::push_zmq_event()";
missed_errors[0].desc = "Missed some events! Zmq queue has reached HWM?";
missed_errors[0].severity = ERR;
if ((ev_attr_conf == false) && (ev_attr_ready == false) && (ev_dev_intr == false) && (pipe_event == false))
missed_event_data = new FwdEventData (event_callback_map[ev_name].device,
full_att_name,event_name,NULL,missed_errors);
else if (ev_attr_ready == false && ev_dev_intr == false && pipe_event == false)
missed_conf_event_data = new FwdAttrConfEventData(event_callback_map[ev_name].device,
full_att_name,event_name,
NULL,missed_errors);
else if (ev_dev_intr == false && pipe_event == false)
missed_ready_event_data = new DataReadyEventData(event_callback_map[ev_name].device,
NULL,event_name,missed_errors);
else if (ev_dev_intr == false)
missed_dev_pipe_data = new PipeEventData(event_callback_map[ev_name].device,full_att_name,
event_name,NULL,missed_errors);
else
missed_dev_intr_event_data = new DevIntrChangeEventData(event_callback_map[ev_name].device,
event_name,full_att_name,
(CommandInfoList *)NULL,
(AttributeInfoListEx *)NULL,
false,missed_errors);
}
//
// Fire the user callback
//
vector<EventSubscribeStruct>::iterator esspos;
unsigned int cb_nb = ipos->second.callback_list.size();
unsigned int cb_ctr = 0;
for (esspos = evt_cb.callback_list.begin(); esspos != evt_cb.callback_list.end(); ++esspos)
{
cb_ctr++;
if (esspos->id > 0)
{
CallBack *callback;
callback = esspos->callback;
EventQueue *ev_queue;
ev_queue = esspos->ev_queue;
if ((ev_attr_conf == false) && (ev_attr_ready == false) && (ev_dev_intr == false) && (pipe_event == false))
{
FwdEventData *event_dat;
//
// In case we have several callbacks on the same event or if the event has to be stored in a queue, copy
// the event data (Event data are in the ZMQ message)
//
if (cb_ctr != cb_nb)
{
DeviceAttribute *dev_attr_copy = NULL;
if (dev_attr != NULL || (callback == NULL && vers >= 4))
{
dev_attr_copy = new DeviceAttribute();
if (no_unmarshalling == false)
dev_attr_copy->deep_copy(*dev_attr);
}
if (no_unmarshalling == false)
event_dat = new FwdEventData(event_callback_map[new_tango_host].device,
full_att_name,
event_name,
dev_attr_copy,
errors);
else
event_dat = new FwdEventData(event_callback_map[new_tango_host].device,
full_att_name,
event_name,
dev_attr_copy,
errors,
&event_data);
}
else
{
if (no_unmarshalling == true)
{
DeviceAttribute *dummy = new DeviceAttribute();
event_dat = new FwdEventData(event_callback_map[new_tango_host].device,
full_att_name,
event_name,
dummy,
errors,
&event_data);
}
else
{
if (callback == NULL && vers >= 4)
{
DeviceAttribute *dev_attr_copy = NULL;
if (dev_attr != NULL)
{
dev_attr_copy = new DeviceAttribute();
dev_attr_copy->deep_copy(*dev_attr);
}
event_dat = new FwdEventData(event_callback_map[new_tango_host].device,
full_att_name,
event_name,
dev_attr_copy,
errors);
}
else
{
event_dat = new FwdEventData(event_callback_map[new_tango_host].device,
full_att_name,
event_name,
dev_attr,
errors);
}
}
}
//
// If a callback method was specified, call it!
//
if (callback != NULL )
{
try
{
if (err_missed_event == true)
callback->push_event(missed_event_data);
callback->push_event(event_dat);
}
catch (...)
{
string st("Tango::ZmqEventConsumer::push_structured_event() exception in callback method of ");
st = st + ipos->first;
print_error_message(st.c_str());
}
delete event_dat;
}
//
// No calback method, the event has to be inserted into the event queue
//
else
{
if (err_missed_event == true)
{
EventData *missed_event_data_copy = new FwdEventData;
*missed_event_data_copy = *missed_event_data;
ev_queue->insert_event(missed_event_data_copy);
}
ev_queue->insert_event(event_dat);
if (vers >= 4 && cb_ctr == cb_nb)
delete dev_attr;
}
}
else if (ev_attr_ready == false && ev_dev_intr == false && pipe_event == false)
{
FwdAttrConfEventData *event_data_;
if (cb_ctr != cb_nb)
{
AttributeInfoEx *attr_info_copy = new AttributeInfoEx();
*attr_info_copy = *attr_info_ex;
event_data_ = new FwdAttrConfEventData(event_callback_map[new_tango_host].device,
full_att_name,
event_name,
attr_info_copy,
errors);
if (attr_conf_5 != NULL)
event_data_->set_fwd_attr_conf(attr_conf_5);
}
else
{
event_data_ = new FwdAttrConfEventData(event_callback_map[new_tango_host].device,
full_att_name,
event_name,
attr_info_ex,
errors);
if (attr_conf_5 != NULL)
event_data_->set_fwd_attr_conf(attr_conf_5);
}
// if callback methods were specified, call them!
if (callback != NULL )
{
try
{
if (err_missed_event == true)
callback->push_event(missed_conf_event_data);
callback->push_event(event_data_);
}
catch (...)
{
string st("Tango::ZmqEventConsumer::push_structured_event() exception in callback method of ");
st = st + ipos->first;
print_error_message(st.c_str());
}
delete event_data_;
}
// no calback method, the event has to be instered
// into the event queue
else
{
if (err_missed_event == true)
{
FwdAttrConfEventData *missed_conf_event_data_copy = new FwdAttrConfEventData;
*missed_conf_event_data_copy = *missed_conf_event_data;
ev_queue->insert_event(missed_conf_event_data_copy);
}
ev_queue->insert_event(event_data_);
}
}
else if (ev_attr_ready == false && pipe_event == false)
{
DevIntrChangeEventData *event_data_ = new DevIntrChangeEventData(event_callback_map[new_tango_host].device,
event_name,full_att_name,&dev_intr_change->cmds,
&dev_intr_change->atts,dev_intr_change->dev_started,errors);
// if a callback method was specified, call it!
if (callback != NULL )
{
try
{
if (err_missed_event == true)
callback->push_event(missed_dev_intr_event_data);
callback->push_event(event_data_);
}
catch (...)
{
string st("Tango::ZmqEventConsumer::push_structured_event() exception in callback method of ");
st = st + ipos->first;
print_error_message(st.c_str());
}
delete event_data_;
}
// no calback method, the event has to be instered
// into the event queue
else
{
if (err_missed_event == true)
{
DevIntrChangeEventData *missed_dev_intr_data_copy = new DevIntrChangeEventData;
*missed_dev_intr_data_copy = *missed_dev_intr_event_data;
ev_queue->insert_event(missed_dev_intr_data_copy);
}
ev_queue->insert_event(event_data_);
}
}
else if (ev_attr_ready == false)
{
PipeEventData *event_data_;
if (cb_ctr != cb_nb)
{
DevicePipe *dev_pipe_copy = new DevicePipe();
*dev_pipe_copy = *dev_pipe;
event_data_ = new PipeEventData(event_callback_map[new_tango_host].device,full_att_name,
event_name,dev_pipe_copy,errors);
}
else
{
event_data_ = new PipeEventData(event_callback_map[new_tango_host].device,
full_att_name,event_name,dev_pipe,errors);
}
// if a callback method was specified, call it!
if (callback != NULL )
{
try
{
if (err_missed_event == true)
callback->push_event(missed_dev_pipe_data);
callback->push_event(event_data_);
}
catch (...)
{
string st("Tango::ZmqEventConsumer::push_structured_event() exception in callback method of ");
st = st + ipos->first;
print_error_message(st.c_str());
}
delete event_data_;
}
// no calback method, the event has to be instered
// into the event queue
else
{
if (err_missed_event == true)
{
PipeEventData *missed_dev_pipe_data_copy = new PipeEventData;
*missed_dev_pipe_data_copy = *missed_dev_pipe_data;
ev_queue->insert_event(missed_dev_pipe_data_copy);
}
ev_queue->insert_event(event_data_);
}
}
else
{
DataReadyEventData *event_data_ = new DataReadyEventData(event_callback_map[new_tango_host].device,
const_cast<AttDataReady *>(att_ready),event_name,errors);
// if a callback method was specified, call it!
if (callback != NULL )
{
try
{
if (err_missed_event == true)
callback->push_event(missed_ready_event_data);
callback->push_event(event_data_);
}
catch (...)
{
string st("Tango::ZmqEventConsumer::push_structured_event() exception in callback method of ");
st = st + ipos->first;
print_error_message(st.c_str());
}
delete event_data_;
}
// no calback method, the event has to be instered
// into the event queue
else
{
if (err_missed_event == true)
{
DataReadyEventData *missed_ready_event_data_copy = new DataReadyEventData;
*missed_ready_event_data_copy = *missed_ready_event_data;
ev_queue->insert_event(missed_ready_event_data_copy);
}
ev_queue->insert_event(event_data_);
}
}
}
} // End of for
map_lock = false;
map_modification_lock.readerOut();
delete missed_event_data;
delete missed_conf_event_data;
delete missed_ready_event_data;
delete missed_dev_intr_event_data;
delete missed_dev_pipe_data;
break;
}
catch (DevFailed &e)
{
delete missed_event_data;
delete missed_conf_event_data;
delete missed_ready_event_data;
delete missed_dev_intr_event_data;
delete missed_dev_pipe_data;
// free the map lock if not already done
if ( map_lock == true )
{
map_modification_lock.readerOut();
}
string reason = e.errors[0].reason.in();
if (reason == API_CommandTimedOut)
{
string st("Tango::ZmqEventConsumer::push_structured_event() timeout on callback monitor of ");
st = st + ipos->first;
print_error_message(st.c_str());
}
break;
}
catch (...)
{
delete missed_event_data;
delete missed_conf_event_data;
delete missed_ready_event_data;
delete missed_dev_intr_event_data;
// free the map lock if not already done
if ( map_lock == true )
{
map_modification_lock.readerOut();
}
string st("Tango::ZmqEventConsumer::push_structured_event(): - ");
st = st + ipos->first;
st = st + " - Unknown exception (Not a DevFailed) while calling Callback ";
print_error_message(st.c_str());
break;
}
}
}
//
// In case of error
//
if (loop == env_var_fqdn_prefix.size() + 1)
{
string st("Event ");
st = st + ev_name;
st = st + " not found in event callback map !!!";
print_error_message(st.c_str());
// even if nothing was found in the map, free the lock
map_modification_lock.readerOut();
}
}
//--------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqEventConsumer::zmq_specific()
//
// description :
// Do some ZMQ specific tasks like checking release compatibility or lower case the admin device name
// which is used in the heartbeat event name.
//
// argument :
// in :
// - dd : The result of the event subscription command
// - adm_name : The admin device name used in the heartbeat event
// - device : The device proxy pointer (for error message)
// - obj_name : The attribute/pipe name (for error message)
// - ev_type : Event type
// - ev_name : Event name
// out:
// - mod_ev_name : Boolean set to true if the event name is modified
//
//--------------------------------------------------------------------------------------------------------------------
void ZmqEventConsumer::zmq_specific(DeviceData &dd,string &adm_name,DeviceProxy *device,const string &obj_name)
{
const DevVarLongStringArray *ev_svr_data;
dd >> ev_svr_data;
//
// For event coming from server still using Tango 8.0.x, do not lowercase the adm_name
//
if (ev_svr_data->lvalue[0] >= 810)
transform(adm_name.begin(),adm_name.end(),adm_name.begin(),::tolower);
//
// If the event is configured to use multicast, check ZMQ release
//
string endpoint(ev_svr_data->svalue[1].in());
int ds_zmq_release = 0;
if (ev_svr_data->lvalue.length() >= 6)
ds_zmq_release = (ev_svr_data->lvalue[5]);
int zmq_major,zmq_minor,zmq_patch;
zmq_version(&zmq_major,&zmq_minor,&zmq_patch);
//
// Check for ZMQ compatible release. Impossible to check if server does not send which ZMQ release it is using.
//
if (ds_zmq_release == 310)
{
if (zmq_major != 3 || zmq_minor != 1 || zmq_patch != 0)
{
Except::throw_exception((const char *)API_UnsupportedFeature,
(const char *)"Incompatibility between ZMQ releases between client and server!",
(const char *)"EventConsumer::connect_event");
}
}
if (zmq_major == 3 && zmq_minor == 1 && zmq_patch == 0)
{
if (ds_zmq_release != 0 && ds_zmq_release != 310)
{
Except::throw_exception((const char *)API_UnsupportedFeature,
(const char *)"Incompatibility between ZMQ releases between client and server!",
(const char *)"EventConsumer::connect_event");
}
}
//
// Check if multicasting is available (requires zmq 3.2.x)
//
if (endpoint.find(MCAST_PROT) != string::npos)
{
if (zmq_major == 3 && zmq_minor < 2)
{
TangoSys_OMemStream o;
o << "The process is using zmq release ";
o << zmq_major << "." << zmq_minor << "." << zmq_patch;
o << "\nThe event on attribute or pipe " << obj_name << " for device " << device->dev_name();
o << " is configured to use multicasting";
o << "\nMulticast event(s) not available with this ZMQ release" << ends;
Except::throw_exception((const char *)API_UnsupportedFeature,
o.str(),
(const char *)"EventConsumer::connect_event");
}
}
}
//--------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqEventConsumer::check_zmq_endpoint()
//
// description :
// Check if the endpoint returned by the ZMQEventSubscriptionChange DS admin device command are valid on the
// client side.
//
// argument :
// in :
// - endpoint : The returned endpoint (contain
//
// return :
// A boolean set to true if it is possible to establish a connection with this endpoint. Otherwise, returns false
//
//--------------------------------------------------------------------------------------------------------------------
bool ZmqEventConsumer::check_zmq_endpoint(const string &endpoint)
{
//
// Isolate IP address in endpoint
//
string::size_type pos = endpoint.rfind(':');
string ip = endpoint.substr(6,pos - 6);
string port_str = endpoint.substr(pos + 1);
int port = atoi(port_str.c_str());
//
// Open a socket
//
struct sockaddr_in address;
int result, len;
long arg;
int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sockfd < 0)
return false;
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(ip.c_str());
address.sin_port = htons(port);
len = sizeof(address);
#ifdef _TG_WINDOWS_
//
// Put socket in non-blocking mode
//
u_long iMode=1;
ioctlsocket(sockfd,FIONBIO,&iMode);
//
// Try to connect
//
result = ::connect(sockfd, (struct sockaddr *)&address, len);
if (result == SOCKET_ERROR)
{
int err_code = WSAGetLastError();
if (err_code == WSAEWOULDBLOCK)
{
struct timeval tv;
fd_set myset;
int res;
tv.tv_sec = 0;
tv.tv_usec = 100000;
FD_ZERO(&myset);
FD_SET(sockfd,&myset);
//
// Because socket is in non-blocking mode, call select to get connection status
//
res = select(sockfd + 1,NULL,&myset,NULL,&tv);
if (res == 0)
{
closesocket(sockfd);
return false;
}
else if (res < 0)
{
closesocket(sockfd);
return false;
}
else if (res > 0)
{
socklen_t lon = sizeof(int);
int valopt = 0;
if (getsockopt(sockfd,SOL_SOCKET,SO_ERROR,(char*)(&valopt),&lon) < 0)
{
closesocket(sockfd);
return false;
}
if (valopt)
{
closesocket(sockfd);
return false;
}
}
}
else
{
closesocket(sockfd);
return false;
}
}
//
// Connection is a success, return true
//
closesocket(sockfd);
#else
//
// Put socket in non-blocking mode
//
if ((arg = fcntl(sockfd,F_GETFL,NULL)) < 0)
{
close(sockfd);
return false;
}
arg |= O_NONBLOCK;
if (fcntl(sockfd,F_SETFL,arg) < 0)
{
close(sockfd);
return false;
}
//
// Try to connect
//
result = ::connect(sockfd, (struct sockaddr *)&address, len);
if (result < 0)
{
if (errno == EINPROGRESS)
{
struct timeval tv;
fd_set myset;
int res;
tv.tv_sec = 0;
tv.tv_usec = 100000;
FD_ZERO(&myset);
FD_SET(sockfd,&myset);
//
// Because socket is in non-blocking mode, call select to get connection status
//
res = select(sockfd + 1,NULL,&myset,NULL,&tv);
if (res == 0)
{
close(sockfd);
return false;
}
else if (res < 0 && errno != EINTR)
{
close(sockfd);
return false;
}
else if (res > 0)
{
socklen_t lon = sizeof(int);
int valopt = 0;
if (getsockopt(sockfd,SOL_SOCKET,SO_ERROR,(void*)(&valopt),&lon) < 0)
{
close(sockfd);
return false;
}
if (valopt)
{
close(sockfd);
return false;
}
}
}
else
{
close(sockfd);
return false;
}
}
//
// Connection is a success, return true
//
close(sockfd);
#endif
return true;
}
//--------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqEventConsumer::get_subscribed_event_ids()
//
// description :
// Get event id for the DeviceProxy given as parameter
//
// argument :
// in :
// - _dev : The DeviceProxy object
// out :
// - _ids : Vector of event id for the given DeviceProxy
//
//--------------------------------------------------------------------------------------------------------------------
void ZmqEventConsumer::get_subscribed_event_ids(DeviceProxy *_dev,vector<int> &_ids)
{
if (_ids.empty() == false)
_ids.clear();
//
// Lock the maps only for reading
//
ReaderLock r(map_modification_lock);
//
// Search with the callback_list map
//
EvCbIte epos;
for (epos = event_callback_map.begin(); epos != event_callback_map.end(); ++epos)
{
if (epos->second.device == _dev)
{
vector<EventSubscribeStruct>::iterator ite;
for (ite = epos->second.callback_list.begin();ite != epos->second.callback_list.end();++ite)
{
_ids.push_back(ite->id);
}
}
}
//
// Search as well in the not connected event(s) vector
//
vector<EventNotConnected>::iterator ite;
for (ite = event_not_connected.begin();ite != event_not_connected.end();++ite)
{
if (ite->device == _dev)
{
_ids.push_back(ite->event_id);
}
}
}
//--------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqAttrValUnion::operator<<=()
//
// description :
// Write our own unmarshalling method. The omniORB one allocate memory and copy data. We already have memory
// allocated in the ZMQ message. No need to allocate once more and to copy data. We are doing this only for
// attribute data. For the remaining, keep using omniORB stuff
//
// argument :
// in :
// - n :
//
//-------------------------------------------------------------------------------------------------------------------
void ZmqAttrValUnion::operator<<= (TangoCdrMemoryStream& _n)
{
char *data_ptr;
if (_n.get_un_marshal_type() == TangoCdrMemoryStream::UN_ATT)
data_ptr = (char *)_n.bufPtr();
else
data_ptr = (char *)_n.get_mkr_in_buf();
//
// Get union discriminator from cdr and if data type is string or device_state let omniORB do its stuff.
// Don't forget to rewind memory ptr before returning to omniORB
//
AttributeDataType _pd__d = ATT_BOOL;
(AttributeDataType&)_pd__d <<= _n;
if (_pd__d == ATT_STRING || _pd__d == DEVICE_STATE)
{
if (_n.get_un_marshal_type() == TangoCdrMemoryStream::UN_ATT)
_n.rewindPtrs();
else
_n.rewind_in(4);
AttrValUnion::operator<<=(_n);
}
else
{
//
// Get data length from cdr
//
_CORBA_ULong length;
if (_pd__d != ATT_NO_DATA)
{
length <<= _n;
if (length == 0)
return;
}
//
// Get att data depending on type
//
switch (_pd__d)
{
case ATT_SHORT:
{
omni::ptr_arith_t in = (omni::ptr_arith_t)_n.get_mkr_in_buf();
omni::ptr_arith_t p1 = _n.align_to(in,omni::ALIGN_2);
_n.set_mkr_in_buf((void *)p1);
init_seq<DevShort,DevVarShortArray>(data_ptr,length,_n);
}
break;
case ATT_DOUBLE:
{
omni::ptr_arith_t in = (omni::ptr_arith_t)_n.get_mkr_in_buf();
omni::ptr_arith_t p1 = _n.align_to(in,omni::ALIGN_8);
_n.set_mkr_in_buf((void *)p1);
init_seq<DevDouble,DevVarDoubleArray>(data_ptr,length,_n);
}
break;
case ATT_FLOAT:
{
omni::ptr_arith_t in = (omni::ptr_arith_t)_n.get_mkr_in_buf();
omni::ptr_arith_t p1 = _n.align_to(in,omni::ALIGN_4);
_n.set_mkr_in_buf((void *)p1);
init_seq<DevFloat,DevVarFloatArray>(data_ptr,length,_n);
}
break;
case ATT_USHORT:
{
omni::ptr_arith_t in = (omni::ptr_arith_t)_n.get_mkr_in_buf();
omni::ptr_arith_t p1 = _n.align_to(in,omni::ALIGN_2);
_n.set_mkr_in_buf((void *)p1);
init_seq<DevUShort,DevVarUShortArray>(data_ptr,length,_n);
}
break;
case ATT_BOOL:
{
init_seq<DevBoolean,DevVarBooleanArray>(data_ptr,length,_n);
}
break;
case ATT_LONG:
{
omni::ptr_arith_t in = (omni::ptr_arith_t)_n.get_mkr_in_buf();
omni::ptr_arith_t p1 = _n.align_to(in,omni::ALIGN_4);
_n.set_mkr_in_buf((void *)p1);
init_seq<DevLong,DevVarLongArray>(data_ptr,length,_n);
}
break;
case ATT_LONG64:
{
omni::ptr_arith_t in = (omni::ptr_arith_t)_n.get_mkr_in_buf();
omni::ptr_arith_t p1 = _n.align_to(in,omni::ALIGN_8);
_n.set_mkr_in_buf((void *)p1);
init_seq<DevLong64,DevVarLong64Array>(data_ptr,length,_n);
}
break;
case ATT_ULONG:
{
omni::ptr_arith_t in = (omni::ptr_arith_t)_n.get_mkr_in_buf();
omni::ptr_arith_t p1 = _n.align_to(in,omni::ALIGN_4);
_n.set_mkr_in_buf((void *)p1);
init_seq<DevULong,DevVarULongArray>(data_ptr,length,_n);
}
break;
case ATT_ULONG64:
{
omni::ptr_arith_t in = (omni::ptr_arith_t)_n.get_mkr_in_buf();
omni::ptr_arith_t p1 = _n.align_to(in,omni::ALIGN_8);
_n.set_mkr_in_buf((void *)p1);
init_seq<DevULong64,DevVarULong64Array>(data_ptr,length,_n);
}
break;
case ATT_UCHAR:
{
init_seq<DevUChar,DevVarUCharArray>(data_ptr,length,_n);
}
break;
case ATT_STATE:
{
init_seq<DevState,DevVarStateArray>(data_ptr,length,_n);
}
break;
//
// We have special cases for DevEncoded (a structure) and ATT_NO_DATA
//
case ATT_ENCODED:
{
DevVarEncodedArray dummy_seq;
encoded_att_value(dummy_seq);
DevVarEncodedArray &dvea = encoded_att_value();
dvea.length(length);
for (_CORBA_ULong i = 0;i < length;i++)
{
dvea[i].encoded_format = _n.unmarshalString(0);
_CORBA_ULong seq_length;
seq_length <<= _n;
_CORBA_Octet *ptr = (_CORBA_Octet *)(data_ptr + _n.currentInputPtr());
dvea[i].encoded_data.replace(seq_length,seq_length,ptr,false);
_n.tango_get_octet_array((seq_length * sizeof(_CORBA_Octet)));
}
}
break;
case ATT_NO_DATA:
{
DevBoolean bo;
bo = _n.unmarshalBoolean();
union_no_data(bo);
}
break;
default:
assert(false);
}
}
}
//--------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqAttributeValue_4::operator<<=()
//
// description :
//
// argument :
// in :
//
//--------------------------------------------------------------------------------------------------------------------
void Tango::ZmqAttributeValue_4::operator<<= (TangoCdrMemoryStream &_n)
{
(ZmqAttrValUnion&)zvalue <<= _n;
(AttrQuality&)quality <<= _n;
(AttrDataFormat&)data_format <<= _n;
(TimeVal&)time <<= _n;
name = _n.unmarshalString(0);
(AttributeDim&)r_dim <<= _n;
(AttributeDim&)w_dim <<= _n;
(DevErrorList&)err_list <<= _n;
}
//--------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqAttributeValue_5::operator<<=()
//
// description :
//
// argument :
// in :
//
//--------------------------------------------------------------------------------------------------------------------
void Tango::ZmqAttributeValue_5::operator<<= (TangoCdrMemoryStream &_n)
{
(ZmqAttrValUnion&)zvalue <<= _n;
(AttrQuality&)quality <<= _n;
(AttrDataFormat&)data_format <<= _n;
data_type <<= _n;
(TimeVal&)time <<= _n;
name = _n.unmarshalString(0);
(AttributeDim&)r_dim <<= _n;
(AttributeDim&)w_dim <<= _n;
(DevErrorList&)err_list <<= _n;
}
//--------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqDevPipeData::operator<<=()
//
// description :
//
// argument :
// in :
//
//--------------------------------------------------------------------------------------------------------------------
void Tango::ZmqDevPipeData::operator<<= (TangoCdrMemoryStream &_n)
{
name = _n.unmarshalString(0);
(TimeVal&)time <<= _n;
(ZmqDevPipeBlob&)data_blob <<= _n;
}
//--------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqDevPipeBlob::operator<<=()
//
// description :
//
// argument :
// in :
//
//--------------------------------------------------------------------------------------------------------------------
void Tango::ZmqDevPipeBlob::operator<<= (TangoCdrMemoryStream &_n)
{
name = _n.unmarshalString(0);
(ZmqDevVarPipeDataEltArray&)blob_data <<= _n;
}
//--------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqDevVarPipeDataEltArray::operator<<=()
//
// description :
//
// argument :
// in :
//
//--------------------------------------------------------------------------------------------------------------------
void Tango::ZmqDevVarPipeDataEltArray::operator<<= (TangoCdrMemoryStream &_n)
{
_CORBA_ULong _l;
_l <<= _n;
if (!_n.checkInputOverrun(1,_l))
{
_CORBA_marshal_sequence_range_check_error(_n);
// never reach here
}
length(_l);
for( _CORBA_ULong _i = 0; _i < _l; _i++ )
{
DevPipeDataElt &dpde = pd_buf[_i];
ZmqDevPipeDataElt &z_dpde = static_cast<ZmqDevPipeDataElt &>(dpde);
z_dpde <<= _n;
}
}
//--------------------------------------------------------------------------------------------------------------------
//
// method :
// ZmqDevPipeDataElt::operator<<=()
//
// description :
//
// argument :
// in :
//
//--------------------------------------------------------------------------------------------------------------------
void Tango::ZmqDevPipeDataElt::operator<<= (TangoCdrMemoryStream &_n)
{
name = _n.unmarshalString(0);
(ZmqAttrValUnion&)value <<= _n;
(ZmqDevVarPipeDataEltArray&)inner_blob <<= _n;
inner_blob_name = _n.unmarshalString(0);
}
//---------------------------------------------------------------------------------------------------------------------
//
// method :
// DelayEvent::DelayEvent
//
// description :
// A class to ask the ZMQ main thread to stop receiving external event. This is necessary to prevent a possible
// deadlock which could happen if an event is received while a user is calling subscribe or unsubscribe event
//
// argument :
// in :
// - ec : Event consumer pointer
//
//--------------------------------------------------------------------------------------------------------------------
DelayEvent::DelayEvent(EventConsumer *ec):released(false),eve_con(NULL)
{
string str;
ec->get_subscription_command_name(str);
//
// Do something only for ZMQ event system
//
if (str[0] == 'Z')
{
eve_con = static_cast<ZmqEventConsumer *>(ec);
zmq::message_t reply;
try
{
zmq::socket_t sender(eve_con->zmq_context,ZMQ_REQ);
//
// In case this thread runs before the main ZMQ thread, it is possible to call connect before the main ZMQ thread has
// binded its socket. In such a case, error code is set to ECONNREFUSED. If this happens, give the main ZMQ thread a
// chance to run and retry the connect call.
// I have tried with a yield call but it still failed in some cases (when running the DS with a file as database for
// instance). Replace the yield with a 15 mS sleep !!!
//
// Since ZMQ 4, itÅ› possible to connect to the remote socket event if it is not yet bound but the remote
// socket will hang in the its recev call!!!!
// We still need the sleep call but not in the exception case
//
try
{
sender.connect(CTRL_SOCK_ENDPOINT);
if (eve_con->is_ctrl_sock_bound() == false)
{
#ifndef _TG_WINDOWS_
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 15000000;
nanosleep(&ts,NULL);
#else
Sleep(20);
#endif
}
}
catch (zmq::error_t &e)
{
if (e.num() == ECONNREFUSED)
{
#ifndef _TG_WINDOWS_
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 15000000;
nanosleep(&ts,NULL);
#else
Sleep(20);
#endif
sender.connect(CTRL_SOCK_ENDPOINT);
}
else
throw;
}
//
// Build message sent to ZMQ main thread. In this case, this is only a command code
//
char buffer[10];
int length = 0;
buffer[length] = ZMQ_DELAY_EVENT;
length++;
eve_con->subscription_monitor.get_monitor();
//
// Send command to main ZMQ thread
//
zmq::message_t send_data(length);
::memcpy(send_data.data(),buffer,length);
sender.send(send_data);
sender.recv(&reply);
}
catch (zmq::error_t &e)
{
eve_con->subscription_monitor.rel_monitor();
TangoSys_OMemStream o;
o << "Failed to delay event!\n";
o << "Error while communicating with the ZMQ main thread\n";
o << "ZMQ message: " << e.what() << ends;
Except::throw_exception((const char *)API_ZmqFailed,
o.str(),
(const char *)"DelayEvent::DelayEvent");
}
//
// In case of error returned by the main ZMQ thread
//
if (reply.size() != 2)
{
eve_con->subscription_monitor.rel_monitor();
char err_mess[512];
::memcpy(err_mess,reply.data(),reply.size());
err_mess[reply.size()] = '\0';
TangoSys_OMemStream o;
o << "Failed to delay events!\n";
o << "Error while asking the ZMQ thread to delay events\n";
o << "ZMQ message: " << err_mess << ends;
Except::throw_exception((const char *)API_ZmqFailed,
o.str(),
(const char *)"DelayEvent::DelayEvent");
}
}
}
DelayEvent::~DelayEvent()
{
if (released == false)
release();
}
void DelayEvent::release()
{
if (eve_con != NULL)
{
zmq::message_t reply;
try
{
zmq::socket_t sender(eve_con->zmq_context,ZMQ_REQ);
sender.connect(CTRL_SOCK_ENDPOINT);
//
// Build message sent to ZMQ main thread. In this case, this is only a command code
//
char buffer[10];
int length = 0;
buffer[length] = ZMQ_RELEASE_EVENT;
length++;
//
// Send command to main ZMQ thread
//
zmq::message_t send_data(length);
::memcpy(send_data.data(),buffer,length);
sender.send(send_data);
sender.recv(&reply);
released = true;
eve_con->subscription_monitor.rel_monitor();
}
catch (zmq::error_t &e)
{
eve_con->subscription_monitor.rel_monitor();
TangoSys_OMemStream o;
o << "Failed to delay event!\n";
o << "Error while communicating with the ZMQ main thread\n";
o << "ZMQ message: " << e.what() << ends;
Except::throw_exception((const char *)API_ZmqFailed,
o.str(),
(const char *)"DelayEvent::release");
}
//
// In case of error returned by the main ZMQ thread
//
if (reply.size() != 2)
{
char err_mess[512];
::memcpy(err_mess,reply.data(),reply.size());
err_mess[reply.size()] = '\0';
TangoSys_OMemStream o;
o << "Failed to release event!\n";
o << "Error while trying to ask the ZMQ thread to release events\n";
o << "ZMQ message: " << err_mess << ends;
Except::throw_exception((const char *)API_ZmqFailed,
o.str(),
(const char *)"DelayEvent::release");
}
}
}
} /* End of Tango namespace */
|