NCBI C++ Toolkit Cross Reference

  C++/src/app/netstorage/nst_handler.cpp


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
/* $Id: nst_handler.cpp 68130 2015-07-14 14:05:21Z satskyse $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Authors: Denis Vakatov * * File Description: NetStorage commands handler * */ #include <ncbi_pch.hpp> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <signal.h> #include <corelib/resource_info.hpp> #include <connect/services/netstorage.hpp> #include <connect/services/netstorage_impl.hpp> #include <../src/misc/netstorage/filetrack.hpp> #include "nst_handler.hpp" #include "nst_server.hpp" #include "nst_protocol_utils.hpp" #include "nst_exception.hpp" #include "nst_version.hpp" #include "nst_application.hpp" #include "nst_warning.hpp" #include "nst_config.hpp" #include "nst_util.hpp" USING_NCBI_SCOPE; const size_t kReadBufferSize = 1024 * 1024; const size_t kWriteBufferSize = 16 * 1024; CNetStorageHandler::SProcessorMap CNetStorageHandler::sm_Processors[] = { { "BYE", & CNetStorageHandler::x_ProcessBye }, { "HELLO", & CNetStorageHandler::x_ProcessHello }, { "INFO", & CNetStorageHandler::x_ProcessInfo }, { "CONFIGURATION", & CNetStorageHandler::x_ProcessConfiguration }, { "HEALTH", & CNetStorageHandler::x_ProcessHealth }, { "ACKALERT", & CNetStorageHandler::x_ProcessAckAlert }, { "RECONFIGURE", & CNetStorageHandler::x_ProcessReconfigure }, { "SHUTDOWN", & CNetStorageHandler::x_ProcessShutdown }, { "GETCLIENTSINFO", & CNetStorageHandler::x_ProcessGetClientsInfo }, { "GETMETADATAINFO", & CNetStorageHandler::x_ProcessGetMetadataInfo }, { "GETOBJECTINFO", & CNetStorageHandler::x_ProcessGetObjectInfo }, { "GETATTRLIST", & CNetStorageHandler::x_ProcessGetAttrList }, { "GETCLIENTOBJECTS", & CNetStorageHandler::x_ProcessGetClientObjects }, { "GETATTR", & CNetStorageHandler::x_ProcessGetAttr }, { "SETATTR", & CNetStorageHandler::x_ProcessSetAttr }, { "DELATTR", & CNetStorageHandler::x_ProcessDelAttr }, { "READ", & CNetStorageHandler::x_ProcessRead }, { "CREATE", & CNetStorageHandler::x_ProcessCreate }, { "WRITE", & CNetStorageHandler::x_ProcessWrite }, { "DELETE", & CNetStorageHandler::x_ProcessDelete }, { "RELOCATE", & CNetStorageHandler::x_ProcessRelocate }, { "EXISTS", & CNetStorageHandler::x_ProcessExists }, { "GETSIZE", & CNetStorageHandler::x_ProcessGetSize }, { "SETEXPTIME", & CNetStorageHandler::x_ProcessSetExpTime }, { "", NULL } }; CRequestContextResetter::CRequestContextResetter() {} CRequestContextResetter::~CRequestContextResetter() { CDiagContext::SetRequestContext(NULL); } CNetStorageHandler::CNetStorageHandler(CNetStorageServer * server) : m_Server(server), m_ReadBuffer(NULL), m_ReadMode(CNetStorageHandler::eReadMessages), m_WriteBuffer(NULL), m_JSONWriter(m_UTTPWriter), m_ObjectBeingWritten(eVoid), m_DataMessageSN(-1), m_MetadataOption(eMetadataNotSpecified), m_DBClientID(-1), m_ObjectSize(0), m_ByeReceived(false), m_FirstMessage(true), m_WriteCreateNeedMetaDBUpdate(false) { m_ReadBuffer = new char[ kReadBufferSize ]; try { m_WriteBuffer = new char[ kWriteBufferSize ]; } catch (...) { delete [] m_ReadBuffer; throw; } m_UTTPWriter.Reset(m_WriteBuffer, kWriteBufferSize); } CNetStorageHandler::~CNetStorageHandler() { delete [] m_WriteBuffer; delete [] m_ReadBuffer; } EIO_Event CNetStorageHandler::GetEventsToPollFor(const CTime** /*alarm_time*/) const { // This implementation is left to simplify the transition to // asynchronous replies. Currently the m_OutputQueue is always // empty so the only eIO_Read will be returned. if (m_OutputQueue.empty()) return eIO_Read; return eIO_ReadWrite; } void CNetStorageHandler::OnOpen(void) { CSocket & socket = GetSocket(); STimeout to = {m_Server->GetNetworkTimeout(), 0}; socket.DisableOSSendDelay(); socket.SetTimeout(eIO_ReadWrite, &to); x_SetQuickAcknowledge(); if (m_Server->IsLog()) { CRequestContextResetter context_resetter; x_CreateConnContext(); } } void CNetStorageHandler::OnRead(void) { CRequestContextResetter context_resetter; if (m_ConnContext.NotNull()) { if (m_CmdContext.NotNull()) CDiagContext::SetRequestContext(m_CmdContext); else CDiagContext::SetRequestContext(m_ConnContext); } size_t n_read; CNSTPreciseTime start = CNSTPreciseTime::Current(); EIO_Status status = GetSocket().Read(m_ReadBuffer, kReadBufferSize, &n_read); if (m_Server->IsLogTimingClientSocket()) m_Timing.Append("Client socket read", start); switch (status) { case eIO_Success: break; case eIO_Timeout: this->OnTimeout(); return; case eIO_Closed: this->OnClose(IServer_ConnectionHandler::eClientClose); return; case eIO_Interrupt: // Will be repeated again later? return; default: // eIO_InvalidArg, eIO_NotSupported, eIO_Unknown x_SetConnRequestStatus(eStatus_SocketIOError); m_Server->CloseConnection(&GetSocket()); return; } m_UTTPReader.SetNewBuffer(m_ReadBuffer, n_read); if (m_ReadMode == eReadMessages || x_ReadRawData()) { try { while (m_JSONReader.ReadMessage(m_UTTPReader)) { if (!m_JSONReader.GetMessage().IsObject()) { // All the incoming objects must be dictionaries x_SetConnRequestStatus(eStatus_BadRequest); m_Server->CloseConnection(&GetSocket()); return; } x_OnMessage(m_JSONReader.GetMessage()); m_FirstMessage = false; m_JSONReader.Reset(); if (m_ReadMode == eReadRawData && !x_ReadRawData()) break; } } catch (CJsonOverUTTPException& e) { // Parsing error if (!m_FirstMessage) { // The systems try to attack all the servers and they send // provocative messages. If the very first unparsable message // received then it does not make sense even to log it to avoid // excessive messages in AppLog. ERR_POST("Incoming message parsing error. " << e << " The connection will be closed."); x_SetConnRequestStatus(eStatus_BadRequest); } else { x_SetConnRequestStatus(eStatus_Probe); } m_Server->CloseConnection(&GetSocket()); } catch (const exception & ex) { ERR_POST("STL exception while processing incoming message: " << ex.what()); x_SetConnRequestStatus(eStatus_BadRequest); m_Server->CloseConnection(&GetSocket()); } catch (...) { ERR_POST("Unknown exception while processing incoming message"); x_SetConnRequestStatus(eStatus_BadRequest); m_Server->CloseConnection(&GetSocket()); } } } void CNetStorageHandler::OnWrite(void) { // This implementation is left to simplify the transition to // asynchronous replies. Currently this method will never be called // because the GetEventsToPollFor(...) never returns anything but // eIO_Read for (;;) { CJsonNode message; { CFastMutexGuard guard(m_OutputQueueMutex); if (m_OutputQueue.empty()) break; message = m_OutputQueue.front(); m_OutputQueue.erase(m_OutputQueue.begin()); } if (!m_JSONWriter.WriteMessage(message)) do x_SendOutputBuffer(); while (!m_JSONWriter.CompleteMessage()); x_SendOutputBuffer(); } } void CNetStorageHandler::OnClose(IServer_ConnectionHandler::EClosePeer peer) { // m_ConnContext != NULL also tells that the logging is required if (m_ConnContext.IsNull()) return; switch (peer) { case IServer_ConnectionHandler::eOurClose: if (m_CmdContext.NotNull()) { m_ConnContext->SetRequestStatus( m_CmdContext->GetRequestStatus()); } else { int status = m_ConnContext->GetRequestStatus(); if (status != eStatus_BadRequest && status != eStatus_SocketIOError) m_ConnContext->SetRequestStatus(eStatus_Inactive); } break; case IServer_ConnectionHandler::eClientClose: if (m_CmdContext.NotNull()) { m_CmdContext->SetRequestStatus(eStatus_SocketIOError); m_ConnContext->SetRequestStatus(eStatus_SocketIOError); } break; } // If a command has not finished its logging by some reasons - do it // here as the last chance. if (m_CmdContext.NotNull()) { CDiagContext::SetRequestContext(m_CmdContext); if (!m_Timing.Empty() && m_Server->IsLogTiming()) { string timing = m_Timing.Serialize(GetDiagContext().Extra()); if (!timing.empty()) GetDiagContext().Extra().Print("timing", timing); } GetDiagContext().PrintRequestStop(); m_CmdContext.Reset(); CDiagContext::SetRequestContext(NULL); } CSocket& socket = GetSocket(); m_ConnContext->SetBytesRd(socket.GetCount(eIO_Read)); m_ConnContext->SetBytesWr(socket.GetCount(eIO_Write)); CDiagContext::SetRequestContext(m_ConnContext); GetDiagContext().PrintRequestStop(); m_ConnContext.Reset(); CDiagContext::SetRequestContext(NULL); } void CNetStorageHandler::OnTimeout(void) { if (m_ConnContext.NotNull()) m_ConnContext->SetRequestStatus(eStatus_Inactive); } void CNetStorageHandler::OnOverflow(EOverflowReason reason) { CRequestContextResetter context_resetter; if (m_ConnContext.NotNull()) { if (m_CmdContext.NotNull()) CDiagContext::SetRequestContext(m_CmdContext); else CDiagContext::SetRequestContext(m_ConnContext); } switch (reason) { case eOR_ConnectionPoolFull: ERR_POST("eCommunicationError:Connection pool full"); break; case eOR_UnpollableSocket: ERR_POST("eCommunicationError:Unpollable connection"); break; case eOR_RequestQueueFull: ERR_POST("eCommunicationError:Request queue full"); break; default: ERR_POST("eCommunicationError:Unknown overflow error"); } } bool CNetStorageHandler::x_ReadRawData() { CUTTPReader::EStreamParsingEvent uttp_event; while ((uttp_event = m_UTTPReader.GetNextEvent()) == CUTTPReader::eChunk || uttp_event == CUTTPReader::eChunkPart) x_OnData(m_UTTPReader.GetChunkPart(), m_UTTPReader.GetChunkPartSize()); switch (uttp_event) { case CUTTPReader::eEndOfBuffer: return false; case CUTTPReader::eControlSymbol: if (m_UTTPReader.GetControlSymbol() == '\n') { x_SendWriteConfirmation(); m_ReadMode = eReadMessages; return true; } /* FALL THROUGH */ default: ERR_POST("Data stream parsing error. The connection will be closed."); x_SetConnRequestStatus(eStatus_BadRequest); m_Server->CloseConnection(&GetSocket()); return false; } } // x_OnMessage gets control when a command message is received. void CNetStorageHandler::x_OnMessage(const CJsonNode & message) { // Log all the message parameters x_PrintMessageRequestStart(message); // Extract message type and its serial number SCommonRequestArguments common_args; try { common_args = ExtractCommonFields(message); } catch (const CNetStorageServerException & ex) { ERR_POST("Error extracting mandatory fields: " << ex.what() << ". " "The connection will be closed."); CJsonNode response = CreateErrorResponseMessage( common_args.m_SerialNumber, CNetStorageServerException::eInvalidMessageHeader, "Error extracting mandatory fields"); x_SetCmdRequestStatus(eStatus_BadRequest); if (x_SendSyncMessage(response) == eIO_Success) m_Server->CloseConnection(&GetSocket()); return; } // Shutting down analysis is here because it needs the command serial // number to return it in the reply message. if (m_Server->ShutdownRequested()) { ERR_POST(Warning << "Server is shutting down. " "The connection will be closed."); // Send response message with an error CJsonNode response = CreateErrorResponseMessage( common_args.m_SerialNumber, CNetStorageServerException::eShuttingDown, "Server is shutting down"); x_SetCmdRequestStatus(eStatus_ShuttingDown); if (x_SendSyncMessage(response) == eIO_Success) m_Server->CloseConnection(&GetSocket()); return; } if (m_ByeReceived) { // BYE message has been received before. Send error response // and close the connection. ERR_POST(Warning << "Received a message after BYE. " "The connection will be closed."); // Send response message with an error CJsonNode response = CreateErrorResponseMessage( common_args.m_SerialNumber, CNetStorageServerException::eMessageAfterBye, "No messages are allowed after BYE"); x_SetCmdRequestStatus(eStatus_BadRequest); if (x_SendSyncMessage(response) == eIO_Success) m_Server->CloseConnection(&GetSocket()); return; } bool error = true; string error_client_message; unsigned int error_code; unsigned int http_error_code; try { m_Timing.Clear(); m_Server->GetClientRegistry().Touch(m_Client); // Find the processor FProcessor processor = x_FindProcessor(common_args); // Call the processor. It returns the number of bytes to expect // after this message. If 0 then another message is expected. (this->*processor)(message, common_args); error = false; } catch (const CNetStorageServerException & ex) { if (ex.GetErrCode() != CNetStorageServerException::eNetStorageAttributeNotFound && ex.GetErrCode() != CNetStorageServerException::eNetStorageAttributeValueNotFound) { // Choke the error printout for this specific case, see CXX-5818 ERR_POST(ex); if (!x_PrintTimingIsOn() && !m_Timing.Empty()) ERR_POST("Timing information: " + m_Timing.Serialize()); } http_error_code = ex.ErrCodeToHTTPStatusCode(); error_code = ex.GetErrCode(); error_client_message = ex.what(); // Note: eAccess alert is set at the point before an exception is // thrown. This is done for a clean alert message. } catch (const CNetStorageException & ex) { ERR_POST(ex); if (!x_PrintTimingIsOn() && !m_Timing.Empty()) ERR_POST("Timing information: " + m_Timing.Serialize()); http_error_code = eStatus_ServerError; if (ex.GetErrCode() == CNetStorageException::eNotExists) error_code = CNetStorageServerException::eRemoteObjectNotFound; else error_code = CNetStorageServerException::eStorageError; error_client_message = ex.what(); } catch (const CException & ex) { ERR_POST(ex); if (!x_PrintTimingIsOn() && !m_Timing.Empty()) ERR_POST("Timing information: " + m_Timing.Serialize()); http_error_code = eStatus_ServerError; error_code = CNetStorageServerException::eInternalError; error_client_message = ex.what(); } catch (const std::exception & ex) { ERR_POST("STL exception: " << ex.what()); if (!x_PrintTimingIsOn() && !m_Timing.Empty()) ERR_POST("Timing information: " + m_Timing.Serialize()); http_error_code = eStatus_ServerError; error_code = CNetStorageServerException::eInternalError; error_client_message = ex.what(); } catch (...) { ERR_POST("Unknown exception"); if (!x_PrintTimingIsOn() && !m_Timing.Empty()) ERR_POST("Timing information: " + m_Timing.Serialize()); http_error_code = eStatus_ServerError; error_code = CNetStorageServerException::eInternalError; error_client_message = "Unknown exception"; } if (error) { x_SetCmdRequestStatus(http_error_code); // Send response message with an error CJsonNode response = CreateErrorResponseMessage( common_args.m_SerialNumber, error_code, error_client_message); x_SendSyncMessage(response); x_PrintMessageRequestStop(); } } // x_OnData gets control when raw data are received. void CNetStorageHandler::x_OnData(const void* data, size_t data_size) { if (!m_ObjectBeingWritten) { if (data_size > 0) { ERR_POST("Received " << data_size << " bytes after " "an error has been reported to the client"); } return; } CNSTPreciseTime start = CNSTPreciseTime::Current(); try { m_ObjectBeingWritten.Write(data, data_size); if (m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI write (" + NStr::NumericToString(data_size) + ")", start); start = 0.0; m_Server->GetClientRegistry().AddBytesWritten(m_Client, data_size); m_ObjectSize += data_size; } catch (const std::exception & ex) { string message = "Error writing into " + m_ObjectBeingWritten.GetLoc() + ": " + ex.what(); if (double(start) != 0.0 && m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI writing error (" + NStr::NumericToString(data_size) + ")", start); ERR_POST(message); if (!x_PrintTimingIsOn() && !m_Timing.Empty()) ERR_POST("Timing information: " + m_Timing.Serialize()); // Send response message with an error CJsonNode response = CreateErrorResponseMessage( m_DataMessageSN, CNetStorageServerException::eWriteError, message); x_SendSyncMessage(response); m_ObjectBeingWritten = eVoid; m_DataMessageSN = -1; } catch (...) { string message = "Unknown exception while writing into " + m_ObjectBeingWritten.GetLoc(); if (double(start) != 0.0 && m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI writing error (" + NStr::NumericToString(data_size) + ")", start); ERR_POST(message); if (!x_PrintTimingIsOn() && !m_Timing.Empty()) ERR_POST("Timing information: " + m_Timing.Serialize()); // Send response message with an error CJsonNode response = CreateErrorResponseMessage( m_DataMessageSN, CNetStorageServerException::eWriteError, message); x_SendSyncMessage(response); m_ObjectBeingWritten = eVoid; m_DataMessageSN = -1; } } void CNetStorageHandler::x_SendWriteConfirmation() { if (!m_ObjectBeingWritten) { x_SetCmdRequestStatus(eStatus_ServerError); x_PrintMessageRequestStop(); return; } CNSTPreciseTime start = CNSTPreciseTime::Current(); try { if (m_ObjectSize == 0) { // This is the object of zero size i.e. there were no write() // calls. Thus the remote object was not really created. m_ObjectBeingWritten.Write("", 0); if (m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI writing (0)", start); } start = CNSTPreciseTime::Current(); m_ObjectBeingWritten.Close(); if (m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI closing", start); } catch (const CException & ex) { x_SetCmdRequestStatus(eStatus_ServerError); if (m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI finilizing error", start); string message = "Error while finalizing " + m_ObjectBeingWritten.GetLoc() + ": " + ex.GetMsg(); ERR_POST(message); if (!x_PrintTimingIsOn()) ERR_POST("Timing information: " + m_Timing.Serialize()); x_PrintMessageRequestStop(); CJsonNode response = CreateErrorResponseMessage( m_DataMessageSN, CNetStorageServerException::eWriteError, message); x_SendSyncMessage(response); m_ObjectBeingWritten = eVoid; m_DataMessageSN = -1; return; } if (m_WriteCreateNeedMetaDBUpdate) { // Update of the meta DB is required. It differs depending it was an // object creation or writing into an existing one. const CNetStorageObjectLoc & object_loc_struct = m_ObjectBeingWritten.Locator(); string locator = object_loc_struct.GetLocator(); if (m_CreateRequest) { // It was creating an object. // In case of problems the response must be ERROR which will be // automatically sent in case of an exception. try { m_Server->GetDb().ExecSP_CreateObjectWithClientID( m_DBObjectID, object_loc_struct.GetUniqueKey(), locator, m_ObjectSize, m_DBClientID, m_CreateTTL, m_Timing); } catch (const CException & ex) { x_SetCmdRequestStatus(eStatus_ServerError); CJsonNode response = CreateErrorResponseMessage( m_DataMessageSN, ex.GetErrCode(), ex.what()); x_SendSyncMessage(response); ERR_POST(ex); if (!x_PrintTimingIsOn() && !m_Timing.Empty()) ERR_POST("Timing information: " + m_Timing.Serialize()); x_PrintMessageRequestStop(); m_ObjectBeingWritten = eVoid; m_DataMessageSN = -1; return; } catch (...) { x_SetCmdRequestStatus(eStatus_ServerError); CJsonNode response = CreateErrorResponseMessage( m_DataMessageSN, CNetStorageServerException::eUnknownError, "Unknown metadata information DB error"); x_SendSyncMessage(response); ERR_POST("Unknown metadata information DB error"); if (!x_PrintTimingIsOn() && !m_Timing.Empty()) ERR_POST("Timing information: " + m_Timing.Serialize()); x_PrintMessageRequestStop(); m_ObjectBeingWritten = eVoid; m_DataMessageSN = -1; return; } } else { // It was writing into existing object try { if (object_loc_struct.HasUserKey()) { m_Server->GetDb().ExecSP_UpdateUserKeyObjectOnWrite( object_loc_struct.GetUniqueKey(), locator, m_ObjectSize, m_DBClientID, m_WriteServiceProps.GetTTL(), m_WriteServiceProps.GetProlongOnWrite(), m_WriteObjectExpiration, m_Timing); } else { m_Server->GetDb().ExecSP_UpdateObjectOnWrite( object_loc_struct.GetUniqueKey(), locator, m_ObjectSize, m_DBClientID, m_WriteServiceProps.GetTTL(), m_WriteServiceProps.GetProlongOnWrite(), m_WriteObjectExpiration, m_Timing); } } catch (const CException & ex) { CJsonNode response = CreateResponseMessage(m_DataMessageSN); AppendWarning(response, eDatabaseWarning, ex.what()); x_SendSyncMessage(response); ERR_POST(ex); if (!x_PrintTimingIsOn() && !m_Timing.Empty()) ERR_POST("Timing information: " + m_Timing.Serialize()); x_PrintMessageRequestStop(); m_ObjectBeingWritten = eVoid; m_DataMessageSN = -1; return; } catch (...) { CJsonNode response = CreateResponseMessage(m_DataMessageSN); AppendWarning(response, eDatabaseWarning, "Unknown updating object meta info error"); x_SendSyncMessage(response); ERR_POST("Unknown updating object meta info error"); if (!x_PrintTimingIsOn() && !m_Timing.Empty()) ERR_POST("Timing information: " + m_Timing.Serialize()); x_PrintMessageRequestStop(); m_ObjectBeingWritten = eVoid; m_DataMessageSN = -1; return; } } } x_SendSyncMessage(CreateResponseMessage(m_DataMessageSN)); x_PrintMessageRequestStop(); m_ObjectBeingWritten = eVoid; m_DataMessageSN = -1; } EIO_Status CNetStorageHandler::x_SendSyncMessage(const CJsonNode & message) { if (!m_JSONWriter.WriteMessage(message)) do { EIO_Status status = x_SendOutputBuffer(); if (status != eIO_Success) return status; } while (!m_JSONWriter.CompleteMessage()); return x_SendOutputBuffer(); } void CNetStorageHandler::x_SendAsyncMessage(const CJsonNode & par) { // The current implementation does not use this. // The code is left here to simplify transition to the asynchronous // way of communicating. { CFastMutexGuard guard(m_OutputQueueMutex); m_OutputQueue.push_back(par); } m_Server->WakeUpPollCycle(); } // Log what we can, set the status code and close the connection void CNetStorageHandler::x_OnSocketWriteError( EIO_Status status, size_t bytes_written, const char * output_buffer, size_t output_buffer_size) { string report = "Error writing message to the client. " "Peer: " + GetSocket().GetPeerAddress() + ". " "Socket write error status: " + IO_StatusStr(status) + ". " "Written bytes: " + NStr::NumericToString(bytes_written) + ". Message begins with: "; if (output_buffer_size > 32) { CTempString buffer_head(output_buffer, 32); report += NStr::PrintableString(buffer_head) + " (TRUNCATED)"; } else { CTempString buffer_head(output_buffer, output_buffer_size); report += NStr::PrintableString(buffer_head); } if (!x_PrintTimingIsOn() && !m_Timing.Empty()) report += " Timing info: " + m_Timing.Serialize(); ERR_POST(report); if (m_ConnContext.NotNull()) { if (m_ConnContext->GetRequestStatus() == eStatus_OK) m_ConnContext->SetRequestStatus(eStatus_SocketIOError); if (m_CmdContext.NotNull()) { if (m_CmdContext->GetRequestStatus() == eStatus_OK) m_CmdContext->SetRequestStatus(eStatus_SocketIOError); } } // Register the socket error with the client m_Server->GetClientRegistry().RegisterSocketWriteError(m_Client); m_Server->CloseConnection(&GetSocket()); } EIO_Status CNetStorageHandler::x_SendOutputBuffer(void) { const char * output_buffer; size_t output_buffer_size; size_t bytes_written; do { m_JSONWriter.GetOutputBuffer(&output_buffer, &output_buffer_size); while (output_buffer_size > 0) { CNSTPreciseTime start = CNSTPreciseTime::Current(); EIO_Status status = GetSocket().Write(output_buffer, output_buffer_size, &bytes_written); if (m_Server->IsLogTimingClientSocket()) m_Timing.Append("Client socket write (" + NStr::NumericToString(output_buffer_size) + ")", start); if (status != eIO_Success) { // Error writing to the socket. Log what we can and close the // connection. x_OnSocketWriteError(status, bytes_written, output_buffer, output_buffer_size); return status; } output_buffer += bytes_written; output_buffer_size -= bytes_written; } } while (m_JSONWriter.NextOutputBuffer()); x_SetQuickAcknowledge(); return eIO_Success; } void CNetStorageHandler::x_SetQuickAcknowledge(void) { int fd = 0; int val = 1; GetSocket().GetOSHandle(&fd, sizeof(fd)); setsockopt(fd, IPPROTO_TCP, TCP_QUICKACK, &val, sizeof(val)); } void CNetStorageHandler::x_CreateConnContext(void) { m_ConnContext.Reset(new CRequestContext()); m_ConnContext->SetRequestID(); m_ConnContext->SetClientIP(GetSocket().GetPeerAddress(eSAF_IP)); // Set the connection request as the current one and print request start CDiagContext::SetRequestContext(m_ConnContext); GetDiagContext().PrintRequestStart() .Print("_type", "conn"); m_ConnContext->SetRequestStatus(eStatus_OK); CDiagContext::SetRequestContext(NULL); } unsigned int CNetStorageHandler::x_GetPeerAddress(void) { unsigned int peer_addr; GetSocket().GetPeerAddress(&peer_addr, 0, eNH_NetworkByteOrder); // always use localhost(127.0*) address for clients coming from // the same net address (sometimes it can be 127.* or full address) if (peer_addr == m_Server->GetHostNetAddr()) return CSocketAPI::GetLoopbackAddress(); return peer_addr; } CNetStorageHandler::FProcessor CNetStorageHandler::x_FindProcessor( const SCommonRequestArguments & common_args) { for (size_t index = 0; sm_Processors[index].m_Processor != NULL; ++index) { if (sm_Processors[index].m_MessageType == common_args.m_MessageType) return sm_Processors[index].m_Processor; } NCBI_THROW(CNetStorageServerException, eInvalidMessageType, "Message type '" + common_args.m_MessageType + "' is not supported"); } void CNetStorageHandler::x_PrintMessageRequestStart(const CJsonNode & message) { if (m_ConnContext.NotNull()) { if (m_CmdContext.IsNull()) { m_CmdContext.Reset(new CRequestContext()); m_CmdContext->SetRequestStatus(eStatus_OK); m_CmdContext->SetRequestID(); } CDiagContext::SetRequestContext(m_CmdContext); // The setting of the client session and IP // must be done before logging. SetSessionAndIP(message, GetSocket()); CDiagContext_Extra ctxt_extra = GetDiagContext().PrintRequestStart() .Print("_type", "message"); for (CJsonIterator it = message.Iterate(); it; ++it) { string key = it.GetKey(); if (key == "ncbi_phid") { string ncbi_phid = it.GetNode().Repr( CJsonNode::fVerbatimIfString); if (!ncbi_phid.empty()) m_CmdContext->SetHitID(ncbi_phid); continue; } if (key != "SessionID" || key != "ClientIP") ctxt_extra.Print(key, it.GetNode().Repr(CJsonNode::fVerbatimIfString)); } ctxt_extra.Flush(); // Workaround: // When extra of the GetDiagContext().PrintRequestStart() is destroyed // or flushed it also resets the status to 0 so I need to set it here // to 200 though it was previously set to 200 when the request context // is created. m_CmdContext->SetRequestStatus(eStatus_OK); } } void CNetStorageHandler::x_PrintMessageRequestStop(void) { if (m_CmdContext.NotNull()) { CDiagContext::SetRequestContext(m_CmdContext); if (!m_Timing.Empty() && m_Server->IsLogTiming()) { string timing = m_Timing.Serialize(GetDiagContext().Extra()); if (!timing.empty()) GetDiagContext().Extra().Print("timing", timing); } GetDiagContext().PrintRequestStop(); m_CmdContext.Reset(); CDiagContext::SetRequestContext(NULL); } } void CNetStorageHandler::x_ProcessBye( const CJsonNode & message, const SCommonRequestArguments & common_args) { m_ByeReceived = true; x_SendSyncMessage(CreateResponseMessage(common_args.m_SerialNumber)); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessHello( const CJsonNode & message, const SCommonRequestArguments & common_args) { string application; // Optional field string ticket; // Optional field string protocol_version; // Optional field if (!message.HasKey("Client")) { NCBI_THROW(CNetStorageServerException, eMandatoryFieldsMissed, "Mandatory field 'Client' is missed"); } string client = NStr::TruncateSpaces(message.GetString("Client")); if (client.empty()) { NCBI_THROW(CNetStorageServerException, eInvalidArgument, "Mandatory field 'Client' is empty"); } m_Client = client; if (message.HasKey("Application")) application = message.GetString("Application"); if (message.HasKey("Ticket")) ticket = message.GetString("Ticket"); if (message.HasKey("ProtocolVersion")) { // Some clients may send the protocol version as an integer // See CXX-6157 CJsonNode ver = message.GetByKey("ProtocolVersion"); CJsonNode::ENodeType node_type = ver.GetNodeType(); if (node_type == CJsonNode::eString) protocol_version = ver.AsString(); else if (node_type == CJsonNode::eInteger) protocol_version = NStr::NumericToString(ver.AsInteger()) + ".0.0"; else NCBI_THROW(CNetStorageServerException, eInvalidArgument, "Invalid type of the 'ProtocolVersion'. " "String is expected."); } if (message.HasKey("Service")) m_Service = NStr::TruncateSpaces(message.GetString("Service")); else m_Service = ""; m_MetadataOption = x_ConvertMetadataArgument(message); // Memorize the client in the registry m_Server->GetClientRegistry().Touch(m_Client, application, ticket, m_Service, protocol_version, m_MetadataOption, x_GetPeerAddress()); // Send success response x_SendSyncMessage(CreateResponseMessage(common_args.m_SerialNumber)); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessInfo( const CJsonNode & message, const SCommonRequestArguments & common_args) { m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eAdministrator); CJsonNode reply = CreateResponseMessage(common_args.m_SerialNumber); reply.SetString("ServerVersion", NETSTORAGED_VERSION); reply.SetString("ProtocolVersion", NETSTORAGED_PROTOCOL_VERSION); reply.SetInteger("PID", CDiagContext::GetPID()); reply.SetString("BuildDate", NETSTORAGED_BUILD_DATE); reply.SetString("StartDate", NST_FormatPreciseTime(m_Server->GetStartTime())); reply.SetString("ServerSession", m_Server->GetSessionID()); reply.SetString("ServerBinaryPath", CNcbiApplication::Instance()->GetProgramExecutablePath()); reply.SetString("ServerCommandLine", m_Server->GetCommandLine()); x_SendSyncMessage(reply); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessConfiguration( const CJsonNode & message, const SCommonRequestArguments & common_args) { m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eAdministrator); CNcbiOstrstream conf; CNcbiOstrstreamToString converter(conf); CNcbiApplication::Instance()->GetConfig().Write(conf); CJsonNode reply = CreateResponseMessage(common_args.m_SerialNumber); reply.SetString("Configuration", string(converter)); reply.SetString("ConfigurationFilePath", CNcbiApplication::Instance()->GetConfigPath()); x_SendSyncMessage(reply); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessHealth( const CJsonNode & message, const SCommonRequestArguments & common_args) { if (m_Client.empty()) { NCBI_THROW(CNetStorageServerException, eHelloRequired, "Anonymous client cannot request server health"); } // GRID dashboard needs this command to be executed regardless of the // configuration settings, so the requirement of being an admin is // removed // if (!m_Server->IsAdminClientName(m_Client)) { // string msg = "Only administrators can request server health"; // m_Server->RegisterAlert(eAccess, msg); // NCBI_THROW(CNetStorageServerException, ePrivileges, msg); // } m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eAdministrator); CJsonNode reply = CreateResponseMessage(common_args.m_SerialNumber); reply.SetByKey("Alerts", m_Server->SerializeAlerts()); // Generic database info CJsonNode db_stat_node(CJsonNode::NewObjectNode()); bool connected = m_Server->GetDb().IsConnected(); db_stat_node.SetBoolean("connected", connected); if (connected) { try { map<string, string> db_stat = m_Server->GetDb(). ExecSP_GetGeneralDBInfo(m_Timing); for (map<string, string>::const_iterator k = db_stat.begin(); k != db_stat.end(); ++k) db_stat_node.SetString(k->first, k->second); db_stat = m_Server->GetDb().ExecSP_GetStatDBInfo(m_Timing); for (map<string, string>::const_iterator k = db_stat.begin(); k != db_stat.end(); ++k) db_stat_node.SetString(k->first, k->second); } catch (const std::exception & ex) { // Health must not fail if there is no meta DB connection AppendWarning(reply, eDatabaseWarning, ex.what()); } catch (...) { // Health must not fail if there is no meta DB connection AppendWarning(reply, eDatabaseWarning, "Unknown metainfo DB access error"); } } reply.SetByKey("MetainfoDB", db_stat_node); x_SendSyncMessage(reply); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessAckAlert( const CJsonNode & message, const SCommonRequestArguments & common_args) { if (m_Client.empty()) { NCBI_THROW(CNetStorageServerException, eHelloRequired, "Anonymous client cannot acknowledge alerts"); } if (!m_Server->IsAdminClientName(m_Client)) { string msg = "Only administrators can acknowledge alerts"; m_Server->RegisterAlert(eAccess, msg); NCBI_THROW(CNetStorageServerException, ePrivileges, msg); } if (!message.HasKey("Name")) NCBI_THROW(CNetStorageServerException, eInvalidArgument, "Mandatory argument Name is not supplied " "in ACKALERT command"); if (!message.HasKey("User")) NCBI_THROW(CNetStorageServerException, eInvalidArgument, "Mandatory argument User is not supplied " "in ACKALERT command"); m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eAdministrator); EAlertAckResult ack_result = m_Server->AcknowledgeAlert( message.GetString("Name"), message.GetString("User")); CJsonNode reply = CreateResponseMessage(common_args.m_SerialNumber); switch (ack_result) { case eAcknowledged: // No warning needed, everything is fine break; case eNotFound: AppendWarning(reply, eAlertNotFoundWarning, "Alert has not been found"); break; case eAlreadyAcknowledged: AppendWarning(reply, eAlertAlreadyAcknowledgedWarning, "Alert has already been acknowledged"); break; default: AppendWarning(reply, eAlertUnknownAcknowledgeResultWarning, "Unknown acknowledge result"); } x_SendSyncMessage(reply); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessReconfigure( const CJsonNode & message, const SCommonRequestArguments & common_args) { if (m_Client.empty()) { NCBI_THROW(CNetStorageServerException, eHelloRequired, "Anonymous client cannot reconfigure server"); } if (!m_Server->AnybodyCanReconfigure()) { if (!m_Server->IsAdminClientName(m_Client)) { string msg = "Only administrators can reconfigure server " "(client: " + m_Client + ")"; m_Server->RegisterAlert(eAccess, msg); NCBI_THROW(CNetStorageServerException, ePrivileges, msg); } } m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eAdministrator); // Unconditionally reload the decryptor in case if the key files are // changed CNcbiEncrypt::Reload(); CJsonNode reply = CreateResponseMessage( common_args.m_SerialNumber); CNcbiApplication * app = CNcbiApplication::Instance(); bool reloaded = app->ReloadConfig( CMetaRegistry::fReloadIfChanged); if (!reloaded && !m_Server->AnybodyCanReconfigure()) { AppendWarning(reply, eConfigNotChangedWarning, "Configuration file has not been changed, " "RECONFIGURE ignored"); x_SendSyncMessage(reply); x_PrintMessageRequestStop(); return; } // Update the config file checksum in memory vector<string> config_checksum_warnings; string config_checksum = NST_GetConfigFileChecksum( app->GetConfigPath(), config_checksum_warnings); if (config_checksum_warnings.empty()) { m_Server->SetRAMConfigFileChecksum(config_checksum); m_Server->SetDiskConfigFileChecksum(config_checksum); } else { for (vector<string>::const_iterator k = config_checksum_warnings.begin(); k != config_checksum_warnings.end(); ++k) ERR_POST(*k); } const CNcbiRegistry & reg = app->GetConfig(); vector<string> config_warnings; NSTValidateConfigFile(reg, config_warnings, false); // false -> no exc // on bad port if (!config_warnings.empty()) { string msg; string alert_msg; for (vector<string>::const_iterator k = config_warnings.begin(); k != config_warnings.end(); ++k) { ERR_POST(*k); if (!msg.empty()) { msg += "; "; alert_msg += "\n"; } msg += *k; alert_msg += *k; } m_Server->RegisterAlert(eReconfigure, alert_msg); NCBI_THROW(CNetStorageServerException, eInvalidConfig, "Configuration file is not well formed; " + msg); } // Reconfigurable at runtime: // [server]: logging, admin name list, max connections, network timeout // [metadata_conf] SNetStorageServerParameters params; string decrypt_warning; params.Read(reg, "server", decrypt_warning); if (!decrypt_warning.empty()) { ERR_POST(decrypt_warning); m_Server->RegisterAlert(eDecryptAdminNames, decrypt_warning); NCBI_THROW(CNetStorageServerException, eInvalidConfig, decrypt_warning); } CJsonNode server_diff = m_Server->SetParameters(params, true); CJsonNode metadata_diff = m_Server->ReadMetadataConfiguration(reg); m_Server->AcknowledgeAlert(eReconfigure, "NSTAcknowledge"); m_Server->SetAnybodyCanReconfigure(false); if (server_diff.IsNull() && metadata_diff.IsNull()) { if (m_ConnContext.NotNull()) GetDiagContext().Extra().Print("accepted_changes", "none"); AppendWarning(reply, eConfigNotChangedWarning, "No changeable parameters were identified " "in the new configuration file"); reply.SetByKey("What", CJsonNode::NewObjectNode()); x_SendSyncMessage(reply); x_PrintMessageRequestStop(); return; } CJsonNode total_changes = CJsonNode::NewObjectNode(); if (!server_diff.IsNull()) total_changes.SetByKey("server", server_diff); if (!metadata_diff.IsNull()) total_changes.SetByKey("metadata_conf", metadata_diff); reply.SetByKey("What", total_changes); x_SendSyncMessage(reply); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessShutdown( const CJsonNode & message, const SCommonRequestArguments & common_args) { if (m_Client.empty()) { NCBI_THROW(CNetStorageServerException, eHelloRequired, "Anonymous client cannot shutdown server"); } if (!m_Server->IsAdminClientName(m_Client)) { string msg = "Only administrators can shutdown server"; m_Server->RegisterAlert(eAccess, msg); NCBI_THROW(CNetStorageServerException, ePrivileges, msg); } if (!message.HasKey("Mode")) { NCBI_THROW(CNetStorageServerException, eMandatoryFieldsMissed, "Mandatory field 'Mode' is missed"); } string mode; mode = message.GetString("Mode"); if (mode != "hard" && mode != "soft") { NCBI_THROW(CNetStorageServerException, eInvalidArgument, "Allowed 'Mode' values are 'soft' and 'hard'"); } if (mode == "hard") exit(1); m_Server->SetShutdownFlag(SIGTERM); // Send success response x_SendSyncMessage(CreateResponseMessage(common_args.m_SerialNumber)); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessGetClientsInfo( const CJsonNode & message, const SCommonRequestArguments & common_args) { m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eAdministrator); // First part is always there: in-memory clients CJsonNode reply = CreateResponseMessage(common_args.m_SerialNumber); reply.SetByKey("Clients", m_Server->GetClientRegistry().Serialize()); // Second part might be here bool db_access = (m_MetadataOption == eMetadataMonitoring || m_Server->InMetadataServices(m_Service)); if (db_access) { try { vector<string> names; int status = m_Server->GetDb().ExecSP_GetClients(names, m_Timing); if (status != 0) { reply.SetString("DBClients", "MetadataAccessWarning"); AppendWarning(reply, eDatabaseWarning, "Stored procedure return code is non zero"); } else { CJsonNode db_clients_node(CJsonNode::NewArrayNode()); for (vector<string>::const_iterator k = names.begin(); k != names.end(); ++k) db_clients_node.AppendString(*k); reply.SetByKey("DBClients", db_clients_node); } } catch (const exception & ex) { reply.SetString("DBClients", "MetadataAccessWarning"); AppendWarning(reply, eDatabaseWarning, "Error while getting a list " "of clients in the metainfo DB: " + string(ex.what())); } catch (...) { reply.SetString("DBClients", "MetadataAccessWarning"); AppendWarning(reply, eDatabaseWarning, "Unknown error while " "getting a list of clients in the metainfo DB"); } } else { reply.SetString("DBClients", "NoMetadataAccess"); } x_SendSyncMessage(reply); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessGetMetadataInfo( const CJsonNode & message, const SCommonRequestArguments & common_args) { m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eAdministrator); CJsonNode reply = CreateResponseMessage(common_args.m_SerialNumber); reply.SetByKey("Services", m_Server->SerializeMetadataInfo()); x_SendSyncMessage(reply); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessGetObjectInfo( const CJsonNode & message, const SCommonRequestArguments & common_args) { m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eReader); CJsonNode reply = CreateResponseMessage(common_args.m_SerialNumber); bool need_db_access = true; if (m_MetadataOption != eMetadataMonitoring) need_db_access = x_DetectMetaDBNeedOnGetObjectInfo(message); CDirectNetStorageObject direct_object = x_GetObject(message); // First source of data - MS SQL database at hand if (need_db_access) { try { TNSTDBValue<CTime> expiration; TNSTDBValue<CTime> creation; TNSTDBValue<CTime> obj_read; TNSTDBValue<CTime> obj_write; TNSTDBValue<CTime> attr_read; TNSTDBValue<CTime> attr_write; TNSTDBValue<Int8> read_count; TNSTDBValue<Int8> write_count; TNSTDBValue<string> client_name; // The parameters are output only (from the SP POV) however the // integer values should be initialized to avoid valgrind complains read_count.m_Value = 0; write_count.m_Value = 0; int status = m_Server->GetDb(). ExecSP_GetObjectFixedAttributes( direct_object.Locator().GetUniqueKey(), expiration, creation, obj_read, obj_write, attr_read, attr_write, read_count, write_count, client_name, m_Timing); if (status != 0) { // The record in the meta DB for the object is not found const string no_metadata = "NoMetadataFound"; reply.SetString("ExpirationTime", no_metadata); reply.SetString("CreationTime", no_metadata); reply.SetString("ObjectReadTime", no_metadata); reply.SetString("ObjectWriteTime", no_metadata); reply.SetString("AttrReadTime", no_metadata); reply.SetString("AttrWriteTime", no_metadata); reply.SetString("ObjectReadCount", no_metadata); reply.SetString("ObjectWriteCount", no_metadata); reply.SetString("ClientName", no_metadata); } else { // The record in the meta DB for the object is found if (expiration.m_IsNull) reply.SetString("ExpirationTime", "NotSet"); else { if (expiration.m_Value < CurrentTime()) NCBI_THROW(CNetStorageServerException, eNetStorageObjectExpired, "Object expired"); reply.SetString("ExpirationTime", expiration.m_Value.AsString()); } if (creation.m_IsNull) reply.SetString("CreationTime", "NotSet"); else reply.SetString("CreationTime", creation.m_Value.AsString()); if (obj_read.m_IsNull) reply.SetString("ObjectReadTime", "NotSet"); else reply.SetString("ObjectReadTime", obj_read.m_Value.AsString()); if (obj_write.m_IsNull) reply.SetString("ObjectWriteTime", "NotSet"); else reply.SetString("ObjectWriteTime", obj_write.m_Value.AsString()); if (attr_read.m_IsNull) reply.SetString("AttrReadTime", "NotSet"); else reply.SetString("AttrReadTime", attr_read.m_Value.AsString()); if (attr_write.m_IsNull) reply.SetString("AttrWriteTime", "NotSet"); else reply.SetString("AttrWriteTime", attr_write.m_Value.AsString()); if (read_count.m_IsNull) reply.SetString("ObjectReadCount", "NotSet"); else reply.SetString("ObjectReadCount", NStr::NumericToString(read_count.m_Value)); if (write_count.m_IsNull) reply.SetString("ObjectWriteCount", "NotSet"); else reply.SetString("ObjectWriteCount", NStr::NumericToString(write_count.m_Value)); if (client_name.m_IsNull) reply.SetString("ClientName", "NotSet"); else reply.SetString("ClientName", client_name.m_Value); } } catch (const CNetStorageServerException & ex) { if (ex.GetErrCode() == CNetStorageServerException:: eNetStorageObjectExpired) throw; // eDatabaseError => no connection or MS SQL error const string warning = "MetadataAccessWarning"; reply.SetString("ExpirationTime", warning); reply.SetString("CreationTime", warning); reply.SetString("ObjectReadTime", warning); reply.SetString("ObjectWriteTime", warning); reply.SetString("AttrReadTime", warning); reply.SetString("AttrWriteTime", warning); reply.SetString("ObjectReadCount", warning); reply.SetString("ObjectWriteCount", warning); reply.SetString("ClientName", warning); AppendWarning(reply, eDatabaseWarning, ex.what()); } catch (const exception & ex) { const string warning = "MetadataAccessWarning"; reply.SetString("ExpirationTime", warning); reply.SetString("CreationTime", warning); reply.SetString("ObjectReadTime", warning); reply.SetString("ObjectWriteTime", warning); reply.SetString("AttrReadTime", warning); reply.SetString("AttrWriteTime", warning); reply.SetString("ObjectReadCount", warning); reply.SetString("ObjectWriteCount", warning); reply.SetString("ClientName", warning); AppendWarning(reply, eDatabaseWarning, "Error while getting " "object fixed attributes: " + string(ex.what())); } catch (...) { const string warning = "MetadataAccessWarning"; reply.SetString("ExpirationTime", warning); reply.SetString("CreationTime", warning); reply.SetString("ObjectReadTime", warning); reply.SetString("ObjectWriteTime", warning); reply.SetString("AttrReadTime", warning); reply.SetString("AttrWriteTime", warning); reply.SetString("ObjectReadCount", warning); reply.SetString("ObjectWriteCount", warning); reply.SetString("ClientName", warning); AppendWarning(reply, eDatabaseWarning, "Unknown error while " "getting object fixed attributes"); } } else { const string no_access = "NoMetadataAccess"; reply.SetString("ExpirationTime", no_access); reply.SetString("CreationTime", no_access); reply.SetString("ObjectReadTime", no_access); reply.SetString("ObjectWriteTime", no_access); reply.SetString("AttrReadTime", no_access); reply.SetString("AttrWriteTime", no_access); reply.SetString("ObjectReadCount", no_access); reply.SetString("ObjectWriteCount", no_access); reply.SetString("ClientName", no_access); } // Second source of data - remote object info CNSTPreciseTime start = CNSTPreciseTime::Current(); try { CJsonNode object_info = direct_object.GetInfo().ToJSON(); if (m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI GetInfo", start); start = 0.0; for (CJsonIterator it = object_info.Iterate(); it; ++it) { string key = it.GetKey(); if (key != "CreationTime") reply.SetByKey(it.GetKey(), it.GetNode()); } } catch (const CNetStorageException & ex) { if (ex.GetErrCode() == CNetStorageException::eNotExists) AppendWarning(reply, eRemoteObjectInfoWarning, "Error while getting remote object info: " + string(ex.what())); if (double(start) != 0.0 && m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI GetInfo exception", start); } catch (const exception & ex) { AppendWarning(reply, eRemoteObjectInfoWarning, "Error while getting remote object info"); if (double(start) != 0.0 && m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI GetInfo exception", start); } catch (...) { AppendWarning(reply, eRemoteObjectInfoWarning, "Unknown error while getting remote object info"); if (double(start) != 0.0 && m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI GetInfo exception", start); } x_SendSyncMessage(reply); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessGetAttrList( const CJsonNode & message, const SCommonRequestArguments & common_args) { m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eReader); x_CheckNonAnonymousClient(); if (!message.HasKey("ObjectLoc") && !message.HasKey("UserKey")) NCBI_THROW(CNetStorageServerException, eMandatoryFieldsMissed, "GETATTRLIST message must have ObjectLoc or UserKey. " "None of them was found."); if (m_MetadataOption == eMetadataDisabled) NCBI_THROW(CNetStorageServerException, eInvalidMetaInfoRequest, "DB access is restricted in HELLO"); if (m_MetadataOption == eMetadataNotSpecified || m_MetadataOption == eMetadataRequired) x_ValidateWriteMetaDBAccess(message); if (m_MetadataOption != eMetadataMonitoring) x_CreateClient(); CJsonNode reply = CreateResponseMessage(common_args.m_SerialNumber); CDirectNetStorageObject direct_object = x_GetObject(message); string object_key = direct_object.Locator().GetUniqueKey(); x_CheckObjectExpiration(object_key, true, reply); vector<string> attr_names; int status = m_Server->GetDb().ExecSP_GetAttributeNames( object_key, attr_names, m_Timing); if (status == 0) { // Everything is fine, the attribute is found CJsonNode names(CJsonNode::NewArrayNode()); for (vector<string>::const_iterator k = attr_names.begin(); k != attr_names.end(); ++k) names.AppendString(*k); reply.SetByKey("AttributeNames", names); } else if (status == -1) { // Object is not found NCBI_THROW(CNetStorageServerException, eNetStorageObjectNotFound, "NetStorage object is not found"); } else { // Unknown status NCBI_THROW(CNetStorageServerException, eInternalError, "Unknown GetAttributeNames status"); } x_SendSyncMessage(reply); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessGetClientObjects( const CJsonNode & message, const SCommonRequestArguments & common_args) { m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eReader); x_CheckNonAnonymousClient(); if (!message.HasKey("ClientName")) NCBI_THROW(CNetStorageServerException, eMandatoryFieldsMissed, "GETCLIENTOBJECTS message must have ClientName."); TNSTDBValue<Int8> limit; limit.m_IsNull = true; limit.m_Value = 0; if (message.HasKey("Limit")) { try { limit.m_Value = message.GetInteger("Limit"); limit.m_IsNull = false; } catch (...) { NCBI_THROW(CNetStorageServerException, eInvalidArgument, "GETCLIENTOBJECTS message Limit argument " "must be an integer."); } if (limit.m_Value <= 0) NCBI_THROW(CNetStorageServerException, eInvalidArgument, "GETCLIENTOBJECTS message Limit argument " "must be > 0."); } if (m_MetadataOption == eMetadataDisabled) NCBI_THROW(CNetStorageServerException, eInvalidMetaInfoRequest, "DB access is restricted in HELLO"); if (m_MetadataOption == eMetadataNotSpecified || m_MetadataOption == eMetadataRequired) x_ValidateWriteMetaDBAccess(message); if (m_MetadataOption != eMetadataMonitoring) x_CreateClient(); CJsonNode reply = CreateResponseMessage(common_args.m_SerialNumber); vector<string> locators; Int8 total_client_objects; int status = m_Server->GetDb().ExecSP_GetClientObjects( message.GetString("ClientName"), limit, total_client_objects, locators, m_Timing); if (status == 0) { // Everything is fine, the attribute is found CJsonNode locators_node(CJsonNode::NewArrayNode()); for (vector<string>::const_iterator k = locators.begin(); k != locators.end(); ++k) locators_node.AppendString(*k); reply.SetByKey("ObjectLocators", locators_node); reply.SetInteger("TotalClientObjects", total_client_objects); } else if (status == -1) { // Client is not found NCBI_THROW(CNetStorageServerException, eNetStorageClientNotFound, "NetStorage client is not found"); } else { // Unknown status NCBI_THROW(CNetStorageServerException, eInternalError, "Unknown GetClientObjects status"); } x_SendSyncMessage(reply); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessGetAttr( const CJsonNode & message, const SCommonRequestArguments & common_args) { m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eReader); x_CheckNonAnonymousClient(); if (!message.HasKey("AttrName")) NCBI_THROW(CNetStorageServerException, eMandatoryFieldsMissed, "Mandatory field 'AttrName' is missed"); string attr_name = message.GetString("AttrName"); if (attr_name.empty()) NCBI_THROW(CNetStorageServerException, eInvalidArgument, "Attribute name must not be empty"); if (!message.HasKey("ObjectLoc") && !message.HasKey("UserKey")) NCBI_THROW(CNetStorageServerException, eMandatoryFieldsMissed, "GETATTR message must have ObjectLoc or UserKey. " "None of them was found."); if (m_MetadataOption == eMetadataDisabled) NCBI_THROW(CNetStorageServerException, eInvalidMetaInfoRequest, "DB access is restricted in HELLO"); if (m_MetadataOption == eMetadataNotSpecified || m_MetadataOption == eMetadataRequired) x_ValidateWriteMetaDBAccess(message); if (m_MetadataOption != eMetadataMonitoring) x_CreateClient(); CJsonNode reply = CreateResponseMessage(common_args.m_SerialNumber); CDirectNetStorageObject direct_object = x_GetObject(message); string object_key = direct_object.Locator().GetUniqueKey(); x_CheckObjectExpiration(object_key, true, reply); string value; int status = m_Server->GetDb().ExecSP_GetAttribute( object_key, attr_name, m_MetadataOption != eMetadataMonitoring, value, m_Timing); if (status == 0) { // Everything is fine, the attribute is found reply.SetString("AttrValue", value); } else if (status == -1) { // Object is not found NCBI_THROW(CNetStorageServerException, eNetStorageObjectNotFound, "NetStorage object is not found"); } else if (status == -2) { // Attribute is not found NCBI_THROW(CNetStorageServerException, eNetStorageAttributeNotFound, "NetStorage attribute is not found"); } else if (status == -3) { // Attribute value is not found NCBI_THROW(CNetStorageServerException, eNetStorageAttributeValueNotFound, "NetStorage attribute value is not found"); } else { // Unknown status NCBI_THROW(CNetStorageServerException, eInternalError, "Unknown GetAttributeValue status"); } x_SendSyncMessage(reply); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessSetAttr( const CJsonNode & message, const SCommonRequestArguments & common_args) { m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eWriter); x_CheckNonAnonymousClient(); if (!message.HasKey("AttrName")) NCBI_THROW(CNetStorageServerException, eMandatoryFieldsMissed, "Mandatory field 'AttrName' is missed"); string attr_name = message.GetString("AttrName"); if (attr_name.empty()) NCBI_THROW(CNetStorageServerException, eInvalidArgument, "Attribute name must not be empty"); if (!message.HasKey("AttrValue")) NCBI_THROW(CNetStorageServerException, eMandatoryFieldsMissed, "Mandatory field 'AttrValue' is missed"); if (!message.HasKey("ObjectLoc") && !message.HasKey("UserKey")) NCBI_THROW(CNetStorageServerException, eMandatoryFieldsMissed, "SETATTR message must have ObjectLoc or UserKey. " "None of them was found."); if (m_MetadataOption == eMetadataDisabled || m_MetadataOption == eMetadataMonitoring) NCBI_THROW(CNetStorageServerException, eInvalidMetaInfoRequest, "State changing operations are restricted in HELLO"); // The only options left are NotSpecified and Required x_ValidateWriteMetaDBAccess(message); x_CreateClient(); CJsonNode reply = CreateResponseMessage(common_args.m_SerialNumber); CDirectNetStorageObject direct_object = x_GetObject(message); string object_key = direct_object.Locator().GetUniqueKey(); x_CheckObjectExpiration(object_key, true, reply); string value = message.GetString("AttrValue"); // The SP will throw an exception if an error occured int status = m_Server->GetDb().ExecSP_AddAttribute( object_key, attr_name, value, m_DBClientID, m_Timing); if (status == -1) { // Object is not found NCBI_THROW(CNetStorageServerException, eNetStorageObjectNotFound, "NetStorage object is not found"); } else if (status != 0) { // Unknown status NCBI_THROW(CNetStorageServerException, eInternalError, "Unknown AddAttribute status"); } x_SendSyncMessage(reply); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessDelAttr( const CJsonNode & message, const SCommonRequestArguments & common_args) { m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eWriter); x_CheckNonAnonymousClient(); if (!message.HasKey("AttrName")) NCBI_THROW(CNetStorageServerException, eMandatoryFieldsMissed, "Mandatory field 'AttrName' is missed"); string attr_name = message.GetString("AttrName"); if (attr_name.empty()) NCBI_THROW(CNetStorageServerException, eInvalidArgument, "Attribute name must not be empty"); if (!message.HasKey("ObjectLoc") && !message.HasKey("UserKey")) NCBI_THROW(CNetStorageServerException, eMandatoryFieldsMissed, "DELATTR message must have ObjectLoc or UserKey. " "None of them was found."); if (m_MetadataOption == eMetadataDisabled || m_MetadataOption == eMetadataMonitoring) NCBI_THROW(CNetStorageServerException, eInvalidMetaInfoRequest, "State changing operations are restricted in HELLO"); // The only options left are NotSpecified and Required x_ValidateWriteMetaDBAccess(message); x_CreateClient(); CJsonNode reply = CreateResponseMessage(common_args.m_SerialNumber); CDirectNetStorageObject direct_object = x_GetObject(message); string object_key = direct_object.Locator().GetUniqueKey(); x_CheckObjectExpiration(object_key, true, reply); int status = m_Server->GetDb().ExecSP_DelAttribute( object_key, attr_name, m_Timing); if (status == -1) { // Object is not found AppendWarning(reply, eObjectNotFoundWarning, "NetStorage object is not found"); } else if (status == -2) { // Attribute is not found AppendWarning(reply, eAttributeNotFoundWarning, "NetStorage attribute is not found"); } else if (status == -3) { // Attribute value is not found AppendWarning(reply, eAttributeValueNotFoundWarning, "NetStorage attribute value is not found"); } else if (status != 0) { // Unknown status NCBI_THROW(CNetStorageServerException, eInternalError, "Unknown DelAttributeValue status"); } x_SendSyncMessage(reply); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessCreate( const CJsonNode & message, const SCommonRequestArguments & common_args) { m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eWriter); x_CheckNonAnonymousClient(); if (m_MetadataOption == eMetadataMonitoring) NCBI_THROW(CNetStorageServerException, eInvalidMetaInfoRequest, "State changing operations are restricted in HELLO"); TNetStorageFlags flags = ExtractStorageFlags(message); SICacheSettings icache_settings = ExtractICacheSettings(message); x_CheckICacheSettings(icache_settings); // The DB update depends on the command flags, on the HELLO // metadata option and may depend on the HELLO service m_WriteCreateNeedMetaDBUpdate = x_DetectMetaDBNeedOnCreate(flags); if (m_WriteCreateNeedMetaDBUpdate) { // Meta information is required so check the DB x_CreateClient(); m_Server->GetDb().ExecSP_GetNextObjectID(m_DBObjectID, m_Timing); } else { m_DBObjectID = 0; } // Create the object stream depending on settings m_ObjectBeingWritten = x_CreateObjectStream(icache_settings, flags); CJsonNode reply = CreateResponseMessage(common_args.m_SerialNumber); string locator = m_ObjectBeingWritten.GetLoc(); reply.SetString("ObjectLoc", locator); x_SendSyncMessage(reply); if (m_ConnContext.NotNull() && !message.HasKey("ObjectLoc")) { GetDiagContext().Extra() .Print("ObjectLoc", locator) .Print("ObjectKey", m_ObjectBeingWritten.Locator().GetUniqueKey()); } // Inform the message receiving loop that raw data are to follow m_ReadMode = eReadRawData; m_DataMessageSN = common_args.m_SerialNumber; m_CreateRequest = true; m_ObjectSize = 0; m_Server->GetClientRegistry().AddObjectsWritten(m_Client, 1); } void CNetStorageHandler::x_ProcessWrite( const CJsonNode & message, const SCommonRequestArguments & common_args) { m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eWriter); x_CheckNonAnonymousClient(); if (!message.HasKey("ObjectLoc") && !message.HasKey("UserKey")) NCBI_THROW(CNetStorageServerException, eMandatoryFieldsMissed, "WRITE message must have ObjectLoc or UserKey. " "None of them was found."); if (m_MetadataOption == eMetadataMonitoring) NCBI_THROW(CNetStorageServerException, eInvalidMetaInfoRequest, "State changing operations are restricted in HELLO"); // If it was eMetadataDisabled then updates are not required m_WriteCreateNeedMetaDBUpdate = false; if (m_MetadataOption == eMetadataRequired || m_MetadataOption == eMetadataNotSpecified) m_WriteCreateNeedMetaDBUpdate = x_DetectMetaDBNeedUpdate( message, m_WriteServiceProps); if (m_WriteCreateNeedMetaDBUpdate) { // Meta information is required so check the DB x_CreateClient(); } CJsonNode reply = CreateResponseMessage( common_args.m_SerialNumber); m_ObjectBeingWritten = x_GetObject(message); const CNetStorageObjectLoc & object_locator = m_ObjectBeingWritten.Locator(); string object_key = object_locator.GetUniqueKey(); string locator = object_locator.GetLocator(); TNSTDBValue<CTime> object_expiration; if (m_WriteCreateNeedMetaDBUpdate) m_WriteObjectExpiration = x_CheckObjectExpiration(object_key, true, reply); reply.SetString("ObjectLoc", locator); x_SendSyncMessage(reply); if (m_ConnContext.NotNull() && !message.HasKey("ObjectLoc")) { GetDiagContext().Extra() .Print("ObjectLoc", locator) .Print("ObjectKey", object_key); } // Inform the message receiving loop that raw data are to follow m_ReadMode = eReadRawData; m_DataMessageSN = common_args.m_SerialNumber; m_CreateRequest = false; m_ObjectSize = 0; m_Server->GetClientRegistry().AddObjectsWritten(m_Client, 1); } void CNetStorageHandler::x_ProcessRead( const CJsonNode & message, const SCommonRequestArguments & common_args) { m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eReader); x_CheckNonAnonymousClient(); if (!message.HasKey("ObjectLoc") && !message.HasKey("UserKey")) NCBI_THROW(CNetStorageServerException, eMandatoryFieldsMissed, "READ message must have ObjectLoc or UserKey. " "None of them was found."); // For eMetadataMonitoring and eMetadataDisabled there must be no updates // in the meta info DB bool need_meta_db_update = false; CNSTServiceProperties service_properties; if (m_MetadataOption == eMetadataRequired || m_MetadataOption == eMetadataNotSpecified) need_meta_db_update = x_DetectMetaDBNeedUpdate(message, service_properties); if (need_meta_db_update) { // Meta information is required so check the DB x_CreateClient(); } CJsonNode reply = CreateResponseMessage( common_args.m_SerialNumber); CDirectNetStorageObject direct_object = x_GetObject(message); const CNetStorageObjectLoc & object_locator = direct_object.Locator(); string object_key = object_locator.GetUniqueKey(); string locator = object_locator.GetLocator(); TNSTDBValue<CTime> object_expiration; if (need_meta_db_update) object_expiration = x_CheckObjectExpiration(object_key, true, reply); else if (m_MetadataOption == eMetadataMonitoring) x_CheckObjectExpiration(object_key, false, reply); x_SendSyncMessage(reply); m_Server->GetClientRegistry().AddObjectsRead(m_Client, 1); char buffer[kReadBufferSize]; size_t bytes_read; Int8 total_bytes = 0; CNSTPreciseTime start = 0.0; try { while (!direct_object.Eof()) { start = CNSTPreciseTime::Current(); bytes_read = direct_object.Read(buffer, sizeof(buffer)); if (m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI read", start); start = 0.0; m_UTTPWriter.SendChunk(buffer, bytes_read, false); if (x_SendOverUTTP() != eIO_Success) return; m_Server->GetClientRegistry().AddBytesRead(m_Client, bytes_read); total_bytes += bytes_read; if (m_CmdContext.NotNull()) m_CmdContext->SetBytesRd(total_bytes); } start = CNSTPreciseTime::Current(); direct_object.Close(); if (m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI Close", start); start = 0.0; reply = CreateResponseMessage(common_args.m_SerialNumber); } catch (const CException & ex) { // Prevent creation of an object in the database if there was none. // NB: the object TTL will not be updated if there was an object need_meta_db_update = false; reply = CreateErrorResponseMessage(common_args.m_SerialNumber, CNetStorageServerException::eReadError, string("Object read error: ") + ex.what()); ERR_POST(ex); if (double(start) != 0.0 && m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI read (exception)", start); if (!x_PrintTimingIsOn() && !m_Timing.Empty()) ERR_POST("Object read error timing information: " + m_Timing.Serialize()); } catch (...) { if (double(start) != 0.0 && m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI read (unknown exception)", start); throw; } m_UTTPWriter.SendControlSymbol('\n'); if (x_SendOverUTTP() != eIO_Success) return; if (need_meta_db_update) { m_Server->GetDb().ExecSP_UpdateObjectOnRead( object_key, locator, total_bytes, m_DBClientID, service_properties.GetTTL(), service_properties.GetProlongOnRead(), object_expiration, m_Timing ); } x_SendSyncMessage(reply); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessDelete( const CJsonNode & message, const SCommonRequestArguments & common_args) { m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eWriter); x_CheckNonAnonymousClient(); if (!message.HasKey("ObjectLoc") && !message.HasKey("UserKey")) NCBI_THROW(CNetStorageServerException, eMandatoryFieldsMissed, "DELETE message must have ObjectLoc or UserKey. " "None of them was found."); if (m_MetadataOption == eMetadataMonitoring) NCBI_THROW(CNetStorageServerException, eInvalidMetaInfoRequest, "State changing operations are restricted in HELLO"); CNSTServiceProperties service_properties; // If it was eMetadataDisabled then updates are not required bool need_meta_db_update = false; if (m_MetadataOption == eMetadataRequired || m_MetadataOption == eMetadataNotSpecified) need_meta_db_update = x_DetectMetaDBNeedUpdate(message, service_properties); CDirectNetStorageObject direct_object = x_GetObject(message); int status = 0; if (need_meta_db_update) { // Meta information is required so delete from the DB first status = m_Server->GetDb().ExecSP_RemoveObject( direct_object.Locator().GetUniqueKey(), m_Timing); } CNSTPreciseTime start = CNSTPreciseTime::Current(); try { direct_object.Remove(); if (m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI Remove", start); } catch (...) { if (m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI Remove exception", start); throw; } m_Server->GetClientRegistry().AddObjectsDeleted(m_Client, 1); CJsonNode reply = CreateResponseMessage(common_args.m_SerialNumber); if (need_meta_db_update && status == -1) { // Stored procedure return -1 if the object is not found in the meta DB AppendWarning(reply, eObjectNotFoundWarning, "Object not found in meta info DB"); } x_SendSyncMessage(reply); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessRelocate( const CJsonNode & message, const SCommonRequestArguments & common_args) { m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eWriter); x_CheckNonAnonymousClient(); // Take the arguments if (!message.HasKey("NewLocation")) { NCBI_THROW(CNetStorageServerException, eInvalidArgument, "NewLocation argument is not found"); } if (m_MetadataOption == eMetadataMonitoring) NCBI_THROW(CNetStorageServerException, eInvalidMetaInfoRequest, "State changing operations are restricted in HELLO"); CNSTServiceProperties service_properties; // If it was eMetadataDisabled then updates are not required bool need_meta_db_update = false; if (m_MetadataOption == eMetadataRequired || m_MetadataOption == eMetadataNotSpecified) need_meta_db_update = x_DetectMetaDBNeedUpdate(message, service_properties); CJsonNode new_location = message.GetByKey("NewLocation"); TNetStorageFlags new_location_flags = ExtractStorageFlags(new_location); SICacheSettings new_location_icache_settings = ExtractICacheSettings(new_location); x_CheckICacheSettings(new_location_icache_settings); if (need_meta_db_update) { // Meta information is required so check the DB x_CreateClient(); } CJsonNode reply = CreateResponseMessage(common_args.m_SerialNumber); CDirectNetStorageObject direct_object = x_GetObject(message); string object_key = direct_object.Locator().GetUniqueKey(); if (need_meta_db_update) x_CheckObjectExpiration(object_key, true, reply); string new_object_loc; CNSTPreciseTime start = CNSTPreciseTime::Current(); try { new_object_loc = direct_object.Relocate(new_location_flags); if (m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI Relocate", start); } catch (...) { if (m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI Relocate exception", start); throw; } if (need_meta_db_update) { m_Server->GetDb().ExecSP_UpdateObjectOnRelocate( object_key, new_object_loc, m_DBClientID, m_Timing); } m_Server->GetClientRegistry().AddObjectsRelocated(m_Client, 1); reply.SetString("ObjectLoc", new_object_loc); x_SendSyncMessage(reply); if (m_ConnContext.NotNull()) { GetDiagContext().Extra() .Print("NewObjectLoc", new_object_loc); } x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessExists( const CJsonNode & message, const SCommonRequestArguments & common_args) { // It was decided to check the object expiration m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eReader); CJsonNode reply = CreateResponseMessage( common_args.m_SerialNumber); CDirectNetStorageObject direct_object = x_GetObject(message); if (m_MetadataOption == eMetadataMonitoring) x_CheckObjectExpiration(direct_object.Locator().GetUniqueKey(), false, reply); else if (x_DetectMetaDBNeedOnGetObjectInfo(message)) x_CheckObjectExpiration(direct_object.Locator().GetUniqueKey(), true, reply); bool exists = false; CNSTPreciseTime start = CNSTPreciseTime::Current(); try { exists = direct_object.Exists(); if (m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI Exists", start); } catch (...) { if (m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI Exists exception", start); throw; } reply.SetBoolean("Exists", exists); x_SendSyncMessage(reply); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessGetSize( const CJsonNode & message, const SCommonRequestArguments & common_args) { // It was decided to check the object expiration m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eReader); CJsonNode reply = CreateResponseMessage(common_args.m_SerialNumber); CDirectNetStorageObject direct_object = x_GetObject(message); string object_key = direct_object.Locator().GetUniqueKey(); if (m_MetadataOption == eMetadataMonitoring) x_CheckObjectExpiration(object_key, false, reply); else if (x_DetectMetaDBNeedOnGetObjectInfo(message)) x_CheckObjectExpiration(object_key, true, reply); Uint8 object_size = 0; CNSTPreciseTime start = CNSTPreciseTime::Current(); try { object_size = direct_object.GetSize(); if (m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI GetSize", start); } catch (...) { if (m_Server->IsLogTimingNSTAPI()) m_Timing.Append("NetStorageAPI GetSize exception", start); throw; } reply.SetInteger("Size", object_size); x_SendSyncMessage(reply); x_PrintMessageRequestStop(); } void CNetStorageHandler::x_ProcessSetExpTime( const CJsonNode & message, const SCommonRequestArguments & common_args) { m_Server->GetClientRegistry().AppendType(m_Client, CNSTClient::eWriter); x_CheckNonAnonymousClient(); if (!message.HasKey("TTL")) NCBI_THROW(CNetStorageServerException, eMandatoryFieldsMissed, "Mandatory field 'TTL' is missed"); string arg_val = message.GetString("TTL"); TNSTDBValue<CTimeSpan> ttl; ttl.m_IsNull = NStr::EqualNocase(arg_val, "infinity"); if (!ttl.m_IsNull) { try { CTimeFormat format("dTh:m:s"); ttl.m_Value = CTimeSpan(arg_val, format); } catch (const exception & ex) { NCBI_THROW(CNetStorageServerException, eInvalidArgument, "TTL format is not recognized: " + string(ex.what())); } catch (...) { NCBI_THROW(CNetStorageServerException, eInvalidArgument, "TTL format is not recognized"); } if (ttl.m_Value.GetSign() == eNegative || ttl.m_Value.IsEmpty()) NCBI_THROW(CNetStorageServerException, eInvalidArgument, "TTL must be > 0"); } if (!message.HasKey("ObjectLoc") && !message.HasKey("UserKey")) NCBI_THROW(CNetStorageServerException, eMandatoryFieldsMissed, "SETEXPTIME message must have ObjectLoc or UserKey. " "None of them was found."); if (m_MetadataOption == eMetadataDisabled || m_MetadataOption == eMetadataMonitoring) NCBI_THROW(CNetStorageServerException, eInvalidMetaInfoRequest, "State changing operations are restricted in HELLO"); // The only options left are NotSpecified and Required x_ValidateWriteMetaDBAccess(message); CJsonNode reply = CreateResponseMessage(common_args.m_SerialNumber); CDirectNetStorageObject direct_object = x_GetObject(message); string object_key = direct_object.Locator().GetUniqueKey(); x_CheckObjectExpiration(object_key, true, reply); x_CreateClient(); // The SP will throw an exception if an error occured int status = m_Server->GetDb().ExecSP_SetExpiration( object_key, ttl, m_Timing); if (status == -1) { // Object is not found NCBI_THROW(CNetStorageServerException, eNetStorageObjectNotFound, "NetStorage object is not found"); } else if (status != 0) { // Unknown status NCBI_THROW(CNetStorageServerException, eInternalError, "Unknown AddAttribute status"); } x_SendSyncMessage(reply); x_PrintMessageRequestStop(); } CDirectNetStorageObject CNetStorageHandler::x_GetObject(const CJsonNode & message) { CNcbiApplication * app = CNcbiApplication::Instance(); if (message.HasKey("ObjectLoc")) { string object_loc = message.GetString("ObjectLoc"); x_CheckObjectLoc(object_loc); try { // There could be a decryption exception so there is this try {} m_Server->ResetDecryptCacheIfNeed(); CDirectNetStorage storage( app->GetConfig(), CNetICacheClient(CNetICacheClient::eAppRegistry), m_Server->GetCompoundIDPool(), kEmptyStr); m_Server->ReportNetStorageAPIDecryptSuccess(); CDirectNetStorageObject object(storage.Open(object_loc)); if (m_ConnContext.NotNull()) GetDiagContext().Extra() .Print("ObjectKey", object.Locator().GetUniqueKey()); return object; } catch (const CRegistryException & ex) { if (ex.GetErrCode() == CRegistryException::eDecryptionFailed) m_Server->RegisterNetStorageAPIDecryptError(ex.what()); throw; } } // Take the arguments SICacheSettings icache_settings; SUserKey user_key; TNetStorageFlags flags; x_GetStorageParams(message, &icache_settings, &user_key, &flags); string client_name(m_Client); if (client_name.empty()) client_name = "anonymous"; CNetICacheClient icache_client(icache_settings.m_ServiceName, icache_settings.m_CacheName, client_name); try { // There could be a decryption exception so there is this try {} m_Server->ResetDecryptCacheIfNeed(); CDirectNetStorageByKey storage(app->GetConfig(), icache_client, m_Server->GetCompoundIDPool(), user_key.m_AppDomain); m_Server->ReportNetStorageAPIDecryptSuccess(); CDirectNetStorageObject object(storage.Open(user_key.m_UniqueID, flags)); // Log if needed if (m_ConnContext.NotNull()) { GetDiagContext().Extra() .Print("ObjectKey", object.Locator().GetUniqueKey()); } return object; } catch (const CRegistryException & ex) { if (ex.GetErrCode() == CRegistryException::eDecryptionFailed) m_Server->RegisterNetStorageAPIDecryptError(ex.what()); throw; } } void CNetStorageHandler::x_CheckNonAnonymousClient(void) const { if (m_Client.empty()) { NCBI_THROW(CNetStorageServerException, eHelloRequired, "Anonymous client cannot perform " "I/O operations with objects"); } } void CNetStorageHandler::x_CheckObjectLoc(const string & object_loc) const { if (object_loc.empty()) { NCBI_THROW(CNetStorageServerException, eInvalidArgument, "Object locator must not be an empty string"); } } void CNetStorageHandler::x_CheckICacheSettings( const SICacheSettings & icache_settings) { if (!icache_settings.m_ServiceName.empty()) { // CacheName is mandatory in this case if (icache_settings.m_CacheName.empty()) { NCBI_THROW(CNetStorageServerException, eInvalidArgument, "CacheName is required if ServiceName is provided"); } } } void CNetStorageHandler::x_CheckUserKey(const SUserKey & user_key) { if (!user_key.m_UniqueID.empty()) { // AppDomain is mandatory in this case if (user_key.m_AppDomain.empty()) { NCBI_THROW(CNetStorageServerException, eInvalidArgument, "AppDomain is required if UniqueKey is provided"); } } } void CNetStorageHandler::x_GetStorageParams( const CJsonNode & message, SICacheSettings * icache_settings, SUserKey * user_key, TNetStorageFlags * flags) { *icache_settings = ExtractICacheSettings(message); *user_key = ExtractUserKey(message); // Check the parameters validity x_CheckICacheSettings(*icache_settings); x_CheckUserKey(*user_key); *flags = ExtractStorageFlags(message); } CDirectNetStorageObject CNetStorageHandler::x_CreateObjectStream( const SICacheSettings & icache_settings, TNetStorageFlags flags) { CNetICacheClient icache_client; if (icache_settings.m_ServiceName.empty()) icache_client = CNetICacheClient(CNetICacheClient::eAppRegistry); else { icache_client = CNetICacheClient(icache_settings.m_ServiceName, icache_settings.m_CacheName, m_Client); } try { // There could be a decryption exception so there is this try {} CNcbiApplication * app = CNcbiApplication::Instance(); m_Server->ResetDecryptCacheIfNeed(); CDirectNetStorage net_storage(app->GetConfig(), icache_client, m_Server->GetCompoundIDPool(), icache_settings.m_CacheName); m_Server->ReportNetStorageAPIDecryptSuccess(); return net_storage.Create(m_Service, m_DBObjectID, flags); } catch (const CRegistryException & ex) { if (ex.GetErrCode() == CRegistryException::eDecryptionFailed) m_Server->RegisterNetStorageAPIDecryptError(ex.what()); throw; } } EIO_Status CNetStorageHandler::x_SendOverUTTP() { const char * output_buffer; size_t output_buffer_size; size_t written; do { m_UTTPWriter.GetOutputBuffer(&output_buffer, &output_buffer_size); if (output_buffer_size > 0) { // Write to the socket as a single transaction CNSTPreciseTime start = CNSTPreciseTime::Current(); EIO_Status result = GetSocket().Write(output_buffer, output_buffer_size, &written); if (m_Server->IsLogTimingClientSocket()) m_Timing.Append("Client socket write (" + NStr::NumericToString(output_buffer_size) + ")", start); if (result != eIO_Success) { // Error writing to the socket. Log what we can and close the // connection. x_OnSocketWriteError(result, written, output_buffer, output_buffer_size); return result; } } } while (m_UTTPWriter.NextOutputBuffer()); return eIO_Success; } EMetadataOption CNetStorageHandler::x_ConvertMetadataArgument(const CJsonNode & message) const { if (!message.HasKey("Metadata")) return eMetadataNotSpecified; string value = message.GetString("Metadata"); value = NStr::TruncateSpaces(value); value = NStr::ToLower(value); EMetadataOption result = g_IdToMetadataOption(value); if (result == eMetadataUnknown) { vector<string> valid = g_GetSupportedMetadataOptions(); string message = "Optional field 'Metadata' value is not " "recognized. Supported values are: "; for (vector<string>::const_iterator k = valid.begin(); k != valid.end(); ++k) { if (k != valid.begin()) message += ", "; message += *k; } NCBI_THROW(CNetStorageServerException, eInvalidArgument, message); } if (result == eMetadataRequired) { if (!m_Server->InMetadataServices(m_Service)) NCBI_THROW(CNetStorageServerException, eInvalidArgument, "Invalid metadata option. It cannot be required for not " "configured service"); } return result; } void CNetStorageHandler::x_ValidateWriteMetaDBAccess( const CJsonNode & message) const { if (message.HasKey("ObjectLoc")) { // Object locator has a metadata flag and a service name string object_loc = message.GetString("ObjectLoc"); x_CheckObjectLoc(object_loc); CNetStorageObjectLoc object_loc_struct(m_Server->GetCompoundIDPool(), object_loc); bool no_metadata = object_loc_struct.IsMetaDataDisabled(); if (no_metadata) NCBI_THROW(CNetStorageServerException, eInvalidArgument, "DB access requested for an object which was created " "with no metadata flag"); string service = object_loc_struct.GetServiceName(); if (service.empty()) service = m_Service; if (!m_Server->InMetadataServices(service)) NCBI_THROW(CNetStorageServerException, eInvalidArgument, "Service (" + service + ") from the object locator is not in the list of " "configured services anymore. DB access declined."); } else { // This is user key identification TNetStorageFlags flags = ExtractStorageFlags(message); if (flags & fNST_NoMetaData) { NCBI_THROW(CNetStorageServerException, eInvalidArgument, "Storage flags forbid access to the metainfo database. " "DB access declined."); } } // Here: it is a user key, so there is no knowledge of the service and // metadata request from the object identifier if (m_MetadataOption == eMetadataRequired) { // The service list could be reconfigured on the fly if (!m_Server->InMetadataServices(m_Service)) NCBI_THROW(CNetStorageServerException, eInvalidArgument, "Service provided in HELLO is not in the list of " "configured services anymore. DB access declined."); return; } if (!m_Server->InMetadataServices(m_Service)) NCBI_THROW(CNetStorageServerException, eInvalidArgument, "DB access requested for a not configured service"); } // Detects if the meta information DB should be updated bool CNetStorageHandler::x_DetectMetaDBNeedUpdate( const CJsonNode & message, CNSTServiceProperties & props) const { if (message.HasKey("ObjectLoc")) { // Object locator has a metadata flag and a service name string object_loc = message.GetString("ObjectLoc"); x_CheckObjectLoc(object_loc); CNetStorageObjectLoc object_loc_struct(m_Server->GetCompoundIDPool(), object_loc); bool no_metadata = object_loc_struct.IsMetaDataDisabled(); if (no_metadata) return false; string service = object_loc_struct.GetServiceName(); if (service.empty()) service = m_Service; bool service_configured = m_Server->GetServiceProperties(service, props); if (m_MetadataOption == eMetadataNotSpecified) return service_configured; // This is the eMetadataRequired option: the check below is needed // because the list of services could be reconfigured on the fly if (!service_configured) NCBI_THROW(CNetStorageServerException, eInvalidArgument, "Service from the object locator is not in the list of " "configured services anymore. DB access declined."); return true; } else { // This is user key identification TNetStorageFlags flags = ExtractStorageFlags(message); if (flags & fNST_NoMetaData) return false; } // Here: it is a user key, so there is no knowledge of the service and // metadata request from the object identifier bool service_configured = m_Server->GetServiceProperties(m_Service, props); if (m_MetadataOption == eMetadataRequired) { // The service list could be reconfigured on the fly if (!service_configured) NCBI_THROW(CNetStorageServerException, eInvalidArgument, "Service provided in HELLO is not in the list of " "configured services anymore. DB access declined."); return true; } return service_configured; } bool CNetStorageHandler::x_DetectMetaDBNeedOnCreate(TNetStorageFlags flags) { if ((flags & fNST_NoMetaData) != 0) return false; if (m_MetadataOption == eMetadataDisabled) return false; bool service_configured = m_Server->GetServiceTTL(m_Service, m_CreateTTL); if (m_MetadataOption == eMetadataRequired) { // The services could be reconfigured on the fly so the presence of the // service in the list of configured must be done here again if (!service_configured) NCBI_THROW(CNetStorageServerException, eInvalidArgument, "Service provided in HELLO (" + m_Service + ") is not in the list of " "configured services anymore. DB access declined."); return true; } return service_configured; } // true if DB should be accessed bool CNetStorageHandler::x_DetectMetaDBNeedOnGetObjectInfo( const CJsonNode & message) const { if (m_MetadataOption == eMetadataDisabled) return false; if (message.HasKey("ObjectLoc")) { // Object locator has a metadata flag and a service name string object_loc = message.GetString("ObjectLoc"); x_CheckObjectLoc(object_loc); CNetStorageObjectLoc object_loc_struct(m_Server->GetCompoundIDPool(), object_loc); bool no_metadata = object_loc_struct.IsMetaDataDisabled(); if (no_metadata) return false; string service = object_loc_struct.GetServiceName(); if (!service.empty()) return m_Server->InMetadataServices(service); } else { // This is user key identification TNetStorageFlags flags = ExtractStorageFlags(message); if (flags & fNST_NoMetaData) return false; } // In all the other cases the access depends on if the HELLO service is // configured for the metadata option return m_Server->InMetadataServices(m_Service); } // The function is called when it was decided that the DB should be accessed. // The function throws an exception if the object is expired. TNSTDBValue<CTime> CNetStorageHandler::x_CheckObjectExpiration(const string & object_key, bool db_exception, CJsonNode & reply) { TNSTDBValue<CTime> expiration; int status; try { status = m_Server->GetDb().ExecSP_GetObjectExpiration(object_key, expiration, m_Timing); } catch (const CNetStorageServerException & ex) { if (db_exception) throw; AppendWarning(reply, eDatabaseWarning, ex.what()); return expiration; } catch (const exception & ex) { if (db_exception) throw; AppendWarning(reply, eDatabaseWarning, "Error while getting an " "object expiration time: " + string(ex.what())); return expiration; } catch (...) { if (db_exception) throw; AppendWarning(reply, eDatabaseWarning, "Unknown error while " "getting an object expiration time"); return expiration; } if (status != 0) return expiration; // The only option here is that the // object is not found if (expiration.m_IsNull) return expiration; // Expiration is not available // The object TTL is found if (expiration.m_Value < CurrentTime()) NCBI_THROW(CNetStorageServerException, eNetStorageObjectExpired, "Object expired"); return expiration; } bool CNetStorageHandler::x_PrintTimingIsOn(void) const { return m_Server->IsLogTiming() && m_CmdContext.NotNull(); } // Checks if the client DB ID is set in the client registry. // If it is then sets the m_DBClientID. This case means the DB ID was cached // before. // If the DB ID is not set then executes the stored procedure which retrieves // the ID and saves it in the in-memory registry. void CNetStorageHandler::x_CreateClient(void) { m_DBClientID = m_Server->GetClientRegistry().GetDBClientID(m_Client); if (m_DBClientID != k_UndefinedClientID) return; // Here: the ID is not set thus a DB request is required m_Server->GetDb().ExecSP_CreateClient(m_Client, m_DBClientID, m_Timing); if (m_DBClientID != k_UndefinedClientID) m_Server->GetClientRegistry().SetDBClientID(m_Client, m_DBClientID); }

source navigation ]   [ diff markup ]   [ identifier search ]   [ freetext search ]   [ file search ]  

This page was automatically generated by the LXR engine.
Visit the LXR main site for more information.