summaryrefslogtreecommitdiffstats
path: root/postgresql.spec
diff options
context:
space:
mode:
authorTom Lane <tgl@fedoraproject.org>2007-02-04 18:34:03 +0000
committerTom Lane <tgl@fedoraproject.org>2007-02-04 18:34:03 +0000
commit3fe398b2dc17ef4c2a47223651dd6c27c648452b (patch)
tree68628c0fee2f8560d1814f41ccb45a135dd40c08 /postgresql.spec
parentd6ea25dd9308cd9d8c5f90b8625d81f214dd2f81 (diff)
downloadpostgresql-setup-postgresql-8_2_2-1_fc7.tar.gz
postgresql-setup-postgresql-8_2_2-1_fc7.tar.xz
postgresql-setup-postgresql-8_2_2-1_fc7.zip
Update to PostgreSQL 8.2.2.postgresql-8_2_2-1_fc7
Diffstat (limited to 'postgresql.spec')
-rwxr-xr-xpostgresql.spec10
1 files changed, 7 insertions, 3 deletions
diff --git a/postgresql.spec b/postgresql.spec
index ed028b1..dbfef69 100755
--- a/postgresql.spec
+++ b/postgresql.spec
@@ -80,8 +80,8 @@
Summary: PostgreSQL client programs and libraries.
Name: postgresql
-Version: 8.2.1
-Release: 2%{?dist}
+Version: 8.2.2
+Release: 1%{?dist}
License: BSD
Group: Applications/Databases
Url: http://www.postgresql.org/
@@ -149,7 +149,7 @@ Obsoletes: postgresql-perl
Obsoletes: postgresql-tk
Obsoletes: rh-postgresql
-Buildroot: %{_tmppath}/%{name}-%{version}-root
+Buildroot: %{_tmppath}/%{name}-%{version}-%{release}-root
%description
PostgreSQL is an advanced Object-Relational database management system
@@ -822,6 +822,10 @@ rm -rf $RPM_BUILD_ROOT
%endif
%changelog
+* Sun Feb 4 2007 Tom Lane <tgl@redhat.com> 8.2.2-1
+- Update to PostgreSQL 8.2.2 to fix CVE-2007-0555, CVE-2007-0556
+Related: #225496
+
* Fri Jan 12 2007 Tom Lane <tgl@redhat.com> 8.2.1-2
- Split -pl subpackage into three new packages to reduce dependencies
and track upstream project's packaging.
85 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.
"""
Implementation of SQLAlchemy backend.
"""
import re
import warnings

from nova import block_device
from nova import db
from nova import exception
from nova import flags
from nova import ipv6
from nova import utils
from nova import log as logging
from nova.compute import vm_states
from nova.db.sqlalchemy import models
from nova.db.sqlalchemy.session import get_session
from sqlalchemy import or_
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import joinedload
from sqlalchemy.orm import joinedload_all
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import desc
from sqlalchemy.sql.expression import literal_column

FLAGS = flags.FLAGS
LOG = logging.getLogger("nova.db.sqlalchemy")


def is_admin_context(context):
    """Indicates if the request context is an administrator."""
    if not context:
        warnings.warn(_('Use of empty request context is deprecated'),
                      DeprecationWarning)
        raise Exception('die')
    return context.is_admin


def is_user_context(context):
    """Indicates if the request context is a normal user."""
    if not context:
        return False
    if context.is_admin:
        return False
    if not context.user_id or not context.project_id:
        return False
    return True


def authorize_project_context(context, project_id):
    """Ensures a request has permission to access the given project."""
    if is_user_context(context):
        if not context.project_id:
            raise exception.NotAuthorized()
        elif context.project_id != project_id:
            raise exception.NotAuthorized()


def authorize_user_context(context, user_id):
    """Ensures a request has permission to access the given user."""
    if is_user_context(context):
        if not context.user_id:
            raise exception.NotAuthorized()
        elif context.user_id != user_id:
            raise exception.NotAuthorized()


def can_read_deleted(context):
    """Indicates if the context has access to deleted objects."""
    if not context:
        return False
    return context.read_deleted


def require_admin_context(f):
    """Decorator to require admin request context.

    The first argument to the wrapped function must be the context.

    """

    def wrapper(*args, **kwargs):
        if not is_admin_context(args[0]):
            raise exception.AdminRequired()
        return f(*args, **kwargs)
    return wrapper


def require_context(f):
    """Decorator to require *any* user or admin context.

    This does no authorization for user or project access matching, see
    :py:func:`authorize_project_context` and
    :py:func:`authorize_user_context`.

    The first argument to the wrapped function must be the context.

    """

    def wrapper(*args, **kwargs):
        if not is_admin_context(args[0]) and not is_user_context(args[0]):
            raise exception.NotAuthorized()
        return f(*args, **kwargs)
    return wrapper


def require_instance_exists(f):
    """Decorator to require the specified instance to exist.

    Requres the wrapped function to use context and instance_id as
    their first two arguments.
    """

    def wrapper(context, instance_id, *args, **kwargs):
        db.api.instance_get(context, instance_id)
        return f(context, instance_id, *args, **kwargs)
    wrapper.__name__ = f.__name__
    return wrapper


def require_volume_exists(f):
    """Decorator to require the specified volume to exist.

    Requres the wrapped function to use context and volume_id as
    their first two arguments.
    """

    def wrapper(context, volume_id, *args, **kwargs):
        db.api.volume_get(context, volume_id)
        return f(context, volume_id, *args, **kwargs)
    wrapper.__name__ = f.__name__
    return wrapper


###################


@require_admin_context
def service_destroy(context, service_id):
    session = get_session()
    with session.begin():
        service_ref = service_get(context, service_id, session=session)
        service_ref.delete(session=session)

        if service_ref.topic == 'compute' and \
            len(service_ref.compute_node) != 0:
            for c in service_ref.compute_node:
                c.delete(session=session)


@require_admin_context
def service_get(context, service_id, session=None):
    if not session:
        session = get_session()

    result = session.query(models.Service).\
                     options(joinedload('compute_node')).\
                     filter_by(id=service_id).\
                     filter_by(deleted=can_read_deleted(context)).\
                     first()

    if not result:
        raise exception.ServiceNotFound(service_id=service_id)

    return result


@require_admin_context
def service_get_all(context, disabled=None):
    session = get_session()
    query = session.query(models.Service).\
                   filter_by(deleted=can_read_deleted(context))

    if disabled is not None:
        query = query.filter_by(disabled=disabled)

    return query.all()


@require_admin_context
def service_get_all_by_topic(context, topic):
    session = get_session()
    return session.query(models.Service).\
                   filter_by(deleted=False).\
                   filter_by(disabled=False).\
                   filter_by(topic=topic).\
                   all()


@require_admin_context
def service_get_by_host_and_topic(context, host, topic):
    session = get_session()
    return session.query(models.Service).\
                   filter_by(deleted=False).\
                   filter_by(disabled=False).\
                   filter_by(host=host).\
                   filter_by(topic=topic).\
                   first()


@require_admin_context
def service_get_all_by_host(context, host):
    session = get_session()
    return session.query(models.Service).\
                   filter_by(deleted=False).\
                   filter_by(host=host).\
                   all()


@require_admin_context
def service_get_all_compute_by_host(context, host):
    topic = 'compute'
    session = get_session()
    result = session.query(models.Service).\
                  options(joinedload('compute_node')).\
                  filter_by(deleted=False).\
                  filter_by(host=host).\
                  filter_by(topic=topic).\
                  all()

    if not result:
        raise exception.ComputeHostNotFound(host=host)

    return result


@require_admin_context
def _service_get_all_topic_subquery(context, session, topic, subq, label):
    sort_value = getattr(subq.c, label)
    return session.query(models.Service, func.coalesce(sort_value, 0)).\
                   filter_by(topic=topic).\
                   filter_by(deleted=False).\
                   filter_by(disabled=False).\
                   outerjoin((subq, models.Service.host == subq.c.host)).\
                   order_by(sort_value).\
                   all()


@require_admin_context
def service_get_all_compute_sorted(context):
    session = get_session()
    with session.begin():
        # NOTE(vish): The intended query is below
        #             SELECT services.*, COALESCE(inst_cores.instance_cores,
        #                                         0)
        #             FROM services LEFT OUTER JOIN
        #             (SELECT host, SUM(instances.vcpus) AS instance_cores
        #              FROM instances GROUP BY host) AS inst_cores
        #             ON services.host = inst_cores.host
        topic = 'compute'
        label = 'instance_cores'
        subq = session.query(models.Instance.host,
                             func.sum(models.Instance.vcpus).label(label)).\
                       filter_by(deleted=False).\
                       group_by(models.Instance.host).\
                       subquery()
        return _service_get_all_topic_subquery(context,
                                               session,
                                               topic,
                                               subq,
                                               label)


@require_admin_context
def service_get_all_network_sorted(context):
    session = get_session()
    with session.begin():
        topic = 'network'
        label = 'network_count'
        subq = session.query(models.Network.host,
                             func.count(models.Network.id).label(label)).\
                       filter_by(deleted=False).\
                       group_by(models.Network.host).\
                       subquery()
        return _service_get_all_topic_subquery(context,
                                               session,
                                               topic,
                                               subq,
                                               label)


@require_admin_context
def service_get_all_volume_sorted(context):
    session = get_session()
    with session.begin():
        topic = 'volume'
        label = 'volume_gigabytes'
        subq = session.query(models.Volume.host,
                             func.sum(models.Volume.size).label(label)).\
                       filter_by(deleted=False).\
                       group_by(models.Volume.host).\
                       subquery()
        return _service_get_all_topic_subquery(context,
                                               session,
                                               topic,
                                               subq,
                                               label)


@require_admin_context
def service_get_by_args(context, host, binary):
    session = get_session()
    result = session.query(models.Service).\
                     filter_by(host=host).\
                     filter_by(binary=binary).\
                     filter_by(deleted=can_read_deleted(context)).\
                     first()
    if not result:
        raise exception.HostBinaryNotFound(host=host, binary=binary)

    return result


@require_admin_context
def service_create(context, values):
    service_ref = models.Service()
    service_ref.update(values)
    if not FLAGS.enable_new_services:
        service_ref.disabled = True
    service_ref.save()
    return service_ref


@require_admin_context
def service_update(context, service_id, values):
    session = get_session()
    with session.begin():
        service_ref = service_get(context, service_id, session=session)
        service_ref.update(values)
        service_ref.save(session=session)


###################


@require_admin_context
def compute_node_get(context, compute_id, session=None):
    if not session:
        session = get_session()

    result = session.query(models.ComputeNode).\
                     filter_by(id=compute_id).\
                     filter_by(deleted=can_read_deleted(context)).\
                     first()

    if not result:
        raise exception.ComputeHostNotFound(host=compute_id)

    return result


@require_admin_context
def compute_node_create(context, values):
    compute_node_ref = models.ComputeNode()
    compute_node_ref.update(values)
    compute_node_ref.save()
    return compute_node_ref


@require_admin_context
def compute_node_update(context, compute_id, values):
    session = get_session()
    with session.begin():
        compute_ref = compute_node_get(context, compute_id, session=session)
        compute_ref.update(values)
        compute_ref.save(session=session)


###################


@require_admin_context
def certificate_get(context, certificate_id, session=None):
    if not session:
        session = get_session()

    result = session.query(models.Certificate).\
                     filter_by(id=certificate_id).\
                     filter_by(deleted=can_read_deleted(context)).\
                     first()

    if not result:
        raise exception.CertificateNotFound(certificate_id=certificate_id)

    return result


@require_admin_context
def certificate_create(context, values):
    certificate_ref = models.Certificate()
    for (key, value) in values.iteritems():
        certificate_ref[key] = value
    certificate_ref.save()
    return certificate_ref


@require_admin_context
def certificate_destroy(context, certificate_id):
    session = get_session()
    with session.begin():
        certificate_ref = certificate_get(context,
                                          certificate_id,
                                          session=session)
        certificate_ref.delete(session=session)


@require_admin_context
def certificate_get_all_by_project(context, project_id):
    session = get_session()
    return session.query(models.Certificate).\
                   filter_by(project_id=project_id).\
                   filter_by(deleted=False).\
                   all()


@require_admin_context
def certificate_get_all_by_user(context, user_id):
    session = get_session()
    return session.query(models.Certificate).\
                   filter_by(user_id=user_id).\
                   filter_by(deleted=False).\
                   all()


@require_admin_context
def certificate_get_all_by_user_and_project(_context, user_id, project_id):
    session = get_session()
    return session.query(models.Certificate).\
                   filter_by(user_id=user_id).\
                   filter_by(project_id=project_id).\
                   filter_by(deleted=False).\
                   all()


@require_admin_context
def certificate_update(context, certificate_id, values):
    session = get_session()
    with session.begin():
        certificate_ref = certificate_get(context,
                                          certificate_id,
                                          session=session)
        for (key, value) in values.iteritems():
            certificate_ref[key] = value
        certificate_ref.save(session=session)


###################


@require_context
def floating_ip_get(context, id):
    session = get_session()
    result = None
    if is_admin_context(context):
        result = session.query(models.FloatingIp).\
                         options(joinedload('fixed_ip')).\
                         options(joinedload_all('fixed_ip.instance')).\
                         filter_by(id=id).\
                         filter_by(deleted=can_read_deleted(context)).\
                         first()
    elif is_user_context(context):
        result = session.query(models.FloatingIp).\
                         options(joinedload('fixed_ip')).\
                         options(joinedload_all('fixed_ip.instance')).\
                         filter_by(project_id=context.project_id).\
                         filter_by(id=id).\
                         filter_by(deleted=False).\
                         first()
    if not result:
        raise exception.FloatingIpNotFound(id=id)

    return result


@require_context
def floating_ip_allocate_address(context, project_id):
    authorize_project_context(context, project_id)
    session = get_session()
    with session.begin():
        floating_ip_ref = session.query(models.FloatingIp).\
                                  filter_by(fixed_ip_id=None).\
                                  filter_by(project_id=None).\
                                  filter_by(deleted=False).\
                                  with_lockmode('update').\
                                  first()
        # NOTE(vish): if with_lockmode isn't supported, as in sqlite,
        #             then this has concurrency issues
        if not floating_ip_ref:
            raise exception.NoMoreFloatingIps()
        floating_ip_ref['project_id'] = project_id
        session.add(floating_ip_ref)
    return floating_ip_ref['address']


@require_context
def floating_ip_create(context, values):
    floating_ip_ref = models.FloatingIp()
    floating_ip_ref.update(values)
    floating_ip_ref.save()
    return floating_ip_ref['address']


@require_context
def floating_ip_count_by_project(context, project_id):
    authorize_project_context(context, project_id)
    session = get_session()
    # TODO(tr3buchet): why leave auto_assigned floating IPs out?
    return session.query(models.FloatingIp).\
                   filter_by(project_id=project_id).\
                   filter_by(auto_assigned=False).\
                   filter_by(deleted=False).\
                   count()


@require_context
def floating_ip_fixed_ip_associate(context, floating_address, fixed_address):
    session = get_session()
    with session.begin():
        # TODO(devcamcar): How to ensure floating_id belongs to user?
        floating_ip_ref = floating_ip_get_by_address(context,
                                                     floating_address,
                                                     session=session)
        fixed_ip_ref = fixed_ip_get_by_address(context,
                                               fixed_address,
                                               session=session)
        floating_ip_ref.fixed_ip = fixed_ip_ref
        floating_ip_ref.save(session=session)


@require_context
def floating_ip_deallocate(context, address):
    session = get_session()
    with session.begin():
        # TODO(devcamcar): How to ensure floating id belongs to user?
        floating_ip_ref = floating_ip_get_by_address(context,
                                                     address,
                                                     session=session)
        floating_ip_ref['project_id'] = None
        floating_ip_ref['host'] = None
        floating_ip_ref['auto_assigned'] = False
        floating_ip_ref.save(session=session)


@require_context
def floating_ip_destroy(context, address):
    session = get_session()
    with session.begin():
        # TODO(devcamcar): Ensure address belongs to user.
        floating_ip_ref = floating_ip_get_by_address(context,
                                                     address,
                                                     session=session)
        floating_ip_ref.delete(session=session)


@require_context
def floating_ip_disassociate(context, address):
    session = get_session()
    with session.begin():
        # TODO(devcamcar): Ensure address belongs to user.
        #                  Does get_floating_ip_by_address handle this?
        floating_ip_ref = floating_ip_get_by_address(context,
                                                     address,
                                                     session=session)
        fixed_ip_ref = floating_ip_ref.fixed_ip
        if fixed_ip_ref:
            fixed_ip_address = fixed_ip_ref['address']
        else:
            fixed_ip_address = None
        floating_ip_ref.fixed_ip = None
        floating_ip_ref.save(session=session)
    return fixed_ip_address


@require_context
def floating_ip_set_auto_assigned(context, address):
    session = get_session()
    with session.begin():
        floating_ip_ref = floating_ip_get_by_address(context,
                                                     address,
                                                     session=session)
        floating_ip_ref.auto_assigned = True
        floating_ip_ref.save(session=session)


@require_admin_context
def floating_ip_get_all(context):
    session = get_session()
    floating_ip_refs = session.query(models.FloatingIp).\
                               options(joinedload_all('fixed_ip.instance')).\
                               filter_by(deleted=False).\
                               all()
    if not floating_ip_refs:
        raise exception.NoFloatingIpsDefined()
    return floating_ip_refs


@require_admin_context
def floating_ip_get_all_by_host(context, host):
    session = get_session()
    floating_ip_refs = session.query(models.FloatingIp).\
                               options(joinedload_all('fixed_ip.instance')).\
                               filter_by(host=host).\
                               filter_by(deleted=False).\
                               all()
    if not floating_ip_refs:
        raise exception.FloatingIpNotFoundForHost(host=host)
    return floating_ip_refs


@require_context
def floating_ip_get_all_by_project(context, project_id):
    authorize_project_context(context, project_id)
    session = get_session()
    # TODO(tr3buchet): why do we not want auto_assigned floating IPs here?
    floating_ip_refs = session.query(models.FloatingIp).\
                               options(joinedload_all('fixed_ip.instance')).\
                               filter_by(project_id=project_id).\
                               filter_by(auto_assigned=False).\
                               filter_by(deleted=False).\
                               all()
    if not floating_ip_refs:
        raise exception.FloatingIpNotFoundForProject(project_id=project_id)
    return floating_ip_refs


@require_context
def floating_ip_get_by_address(context, address, session=None):
    # TODO(devcamcar): Ensure the address belongs to user.
    if not session:
        session = get_session()

    result = session.query(models.FloatingIp).\
                     options(joinedload_all('fixed_ip.network')).\
                     filter_by(address=address).\
                     filter_by(deleted=can_read_deleted(context)).\
                     first()
    if not result:
        raise exception.FloatingIpNotFoundForAddress(address=address)
    return result


@require_context
def floating_ip_update(context, address, values):
    session = get_session()
    with session.begin():
        floating_ip_ref = floating_ip_get_by_address(context, address, session)
        for (key, value) in values.iteritems():
            floating_ip_ref[key] = value
        floating_ip_ref.save(session=session)


###################


@require_admin_context
def fixed_ip_associate(context, address, instance_id, network_id=None,
                       reserved=False):
    """Keyword arguments:
    reserved -- should be a boolean value(True or False), exact value will be 
    used to filter on the fixed ip address
    """
    session = get_session()
    with session.begin():
        network_or_none = or_(models.FixedIp.network_id == network_id,
                              models.FixedIp.network_id == None)
        fixed_ip_ref = session.query(models.FixedIp).\
                               filter(network_or_none).\
                               filter_by(reserved=reserved).\
                               filter_by(deleted=False).\
                               filter_by(address=address).\
                               with_lockmode('update').\
                               first()
        # NOTE(vish): if with_lockmode isn't supported, as in sqlite,
        #             then this has concurrency issues
        if fixed_ip_ref is None:
            raise exception.FixedIpNotFoundForNetwork(address=address,
                                            network_id=network_id)
        if fixed_ip_ref.instance is not None:
            raise exception.FixedIpAlreadyInUse(address=address)

        if not fixed_ip_ref.network:
            fixed_ip_ref.network = network_get(context,
                                           network_id,
                                           session=session)
        fixed_ip_ref.instance = instance_get(context,
                                             instance_id,
                                             session=session)
        session.add(fixed_ip_ref)
    return fixed_ip_ref['address']


@require_admin_context
def fixed_ip_associate_pool(context, network_id, instance_id=None, host=None):
    session = get_session()
    with session.begin():
        network_or_none = or_(models.FixedIp.network_id == network_id,
                              models.FixedIp.network_id == None)
        fixed_ip_ref = session.query(models.FixedIp).\
                               filter(network_or_none).\
                               filter_by(reserved=False).\
                               filter_by(deleted=False).\
                               filter_by(instance=None).\
                               filter_by(host=None).\
                               with_lockmode('update').\
                               first()
        # NOTE(vish): if with_lockmode isn't supported, as in sqlite,
        #             then this has concurrency issues
        if not fixed_ip_ref:
            raise exception.NoMoreFixedIps()
        if not fixed_ip_ref.network:
            fixed_ip_ref.network = network_get(context,
                                           network_id,
                                           session=session)
        if instance_id:
            fixed_ip_ref.instance = instance_get(context,
                                                 instance_id,
                                                 session=session)
        if host:
            fixed_ip_ref.host = host
        session.add(fixed_ip_ref)
    return fixed_ip_ref['address']


@require_context
def fixed_ip_create(_context, values):
    fixed_ip_ref = models.FixedIp()
    fixed_ip_ref.update(values)
    fixed_ip_ref.save()
    return fixed_ip_ref['address']


@require_context
def fixed_ip_disassociate(context, address):
    session = get_session()
    with session.begin():
        fixed_ip_ref = fixed_ip_get_by_address(context,
                                               address,
                                               session=session)
        fixed_ip_ref.instance = None
        fixed_ip_ref.save(session=session)


@require_admin_context
def fixed_ip_disassociate_all_by_timeout(_context, host, time):
    session = get_session()
    inner_q = session.query(models.Network.id).\
                      filter_by(host=host).\
                      subquery()
    result = session.query(models.FixedIp).\
                     filter(models.FixedIp.network_id.in_(inner_q)).\
                     filter(models.FixedIp.updated_at < time).\
                     filter(models.FixedIp.instance_id != None).\
                     filter_by(allocated=False).\
                     update({'instance_id': None,
                             'leased': False,
                             'updated_at': utils.utcnow()},
                             synchronize_session='fetch')
    return result


@require_admin_context
def fixed_ip_get_all(context, session=None):
    if not session:
        session = get_session()
    result = session.query(models.FixedIp).\
                     options(joinedload('floating_ips')).\
                     all()
    if not result:
        raise exception.NoFixedIpsDefined()

    return result


@require_admin_context
def fixed_ip_get_all_by_instance_host(context, host=None):
    session = get_session()

    result = session.query(models.FixedIp).\
                     options(joinedload('floating_ips')).\
                     join(models.FixedIp.instance).\
                     filter_by(state=1).\
                     filter_by(host=host).\
                     all()

    if not result:
        raise exception.FixedIpNotFoundForHost(host=host)

    return result


@require_context
def fixed_ip_get_by_address(context, address, session=None):
    if not session:
        session = get_session()
    result = session.query(models.FixedIp).\
                     filter_by(address=address).\
                     filter_by(deleted=can_read_deleted(context)).\
                     options(joinedload('floating_ips')).\
                     options(joinedload('network')).\
                     options(joinedload('instance')).\
                     first()
    if not result:
        raise exception.FixedIpNotFoundForAddress(address=address)

    if is_user_context(context):
        authorize_project_context(context, result.instance.project_id)

    return result


@require_context
def fixed_ip_get_by_instance(context, instance_id):
    session = get_session()
    rv = session.query(models.FixedIp).\
                 options(joinedload('floating_ips')).\
                 filter_by(instance_id=instance_id).\
                 filter_by(deleted=False).\
                 all()
    if not rv:
        raise exception.FixedIpNotFoundForInstance(instance_id=instance_id)
    return rv


@require_context
def fixed_ip_get_by_network_host(context, network_id, host):
    session = get_session()
    rv = session.query(models.FixedIp).\
                 filter_by(network_id=network_id).\
                 filter_by(host=host).\
                 filter_by(deleted=False).\
                 first()
    if not rv:
        raise exception.FixedIpNotFoundForNetworkHost(network_id=network_id,
                                                      host=host)
    return rv


@require_context
def fixed_ip_get_by_virtual_interface(context, vif_id):
    session = get_session()
    rv = session.query(models.FixedIp).\
                 options(joinedload('floating_ips')).\
                 filter_by(virtual_interface_id=vif_id).\
                 filter_by(deleted=False).\
                 all()
    if not rv:
        raise exception.FixedIpNotFoundForVirtualInterface(vif_id=vif_id)
    return rv


@require_admin_context
def fixed_ip_get_network(context, address):
    fixed_ip_ref = fixed_ip_get_by_address(context, address)
    return fixed_ip_ref.network


@require_context
def fixed_ip_update(context, address, values):
    session = get_session()
    with session.begin():
        fixed_ip_ref = fixed_ip_get_by_address(context,
                                               address,
                                               session=session)
        fixed_ip_ref.update(values)
        fixed_ip_ref.save(session=session)


###################


@require_context
def virtual_interface_create(context, values):
    """Create a new virtual interface record in teh database.

    :param values: = dict containing column values
    """
    try:
        vif_ref = models.VirtualInterface()
        vif_ref.update(values)
        vif_ref.save()
    except IntegrityError:
        raise exception.VirtualInterfaceCreateException()

    return vif_ref


@require_context
def virtual_interface_update(context, vif_id, values):
    """Update a virtual interface record in the database.

    :param vif_id: = id of virtual interface to update
    :param values: = values to update
    """
    session = get_session()
    with session.begin():
        vif_ref = virtual_interface_get(context, vif_id, session=session)
        vif_ref.update(values)
        vif_ref.save(session=session)
        return vif_ref


@require_context
def virtual_interface_get(context, vif_id, session=None):
    """Gets a virtual interface from the table.

    :param vif_id: = id of the virtual interface
    """
    if not session:
        session = get_session()

    vif_ref = session.query(models.VirtualInterface).\
                      filter_by(id=vif_id).\
                      options(joinedload('network')).\
                      options(joinedload('instance')).\
                      options(joinedload('fixed_ips')).\
                      first()
    return vif_ref


@require_context
def virtual_interface_get_by_address(context, address):
    """Gets a virtual interface from the table.

    :param address: = the address of the interface you're looking to get
    """
    session = get_session()
    vif_ref = session.query(models.VirtualInterface).\
                      filter_by(address=address).\
                      options(joinedload('network')).\
                      options(joinedload('instance')).\
                      options(joinedload('fixed_ips')).\
                      first()
    return vif_ref


@require_context
def virtual_interface_get_by_uuid(context, vif_uuid):
    """Gets a virtual interface from the table.

    :param vif_uuid: the uuid of the interface you're looking to get
    """
    session = get_session()
    vif_ref = session.query(models.VirtualInterface).\
                      filter_by(uuid=vif_uuid).\
                      options(joinedload('network')).\
                      options(joinedload('instance')).\
                      options(joinedload('fixed_ips')).\
                      first()
    return vif_ref


@require_context
def virtual_interface_get_by_fixed_ip(context, fixed_ip_id):
    """Gets the virtual interface fixed_ip is associated with.

    :param fixed_ip_id: = id of the fixed_ip
    """
    session = get_session()
    vif_ref = session.query(models.VirtualInterface).\
                      filter_by(fixed_ip_id=fixed_ip_id).\
                      options(joinedload('network')).\
                      options(joinedload('instance')).\
                      options(joinedload('fixed_ips')).\
                      first()
    return vif_ref


@require_context
@require_instance_exists
def virtual_interface_get_by_instance(context, instance_id):
    """Gets all virtual interfaces for instance.

    :param instance_id: = id of the instance to retreive vifs for
    """
    session = get_session()
    vif_refs = session.query(models.VirtualInterface).\
                       filter_by(instance_id=instance_id).\
                       options(joinedload('network')).\
                       options(joinedload('instance')).\
                       options(joinedload('fixed_ips')).\
                       all()
    return vif_refs


@require_context
def virtual_interface_get_by_instance_and_network(context, instance_id,
                                                           network_id):
    """Gets virtual interface for instance that's associated with network."""
    session = get_session()
    vif_ref = session.query(models.VirtualInterface).\
                      filter_by(instance_id=instance_id).\
                      filter_by(network_id=network_id).\
                      options(joinedload('network')).\
                      options(joinedload('instance')).\
                      options(joinedload('fixed_ips')).\
                      first()
    return vif_ref


@require_admin_context
def virtual_interface_get_by_network(context, network_id):
    """Gets all virtual_interface on network.

    :param network_id: = network to retreive vifs for
    """
    session = get_session()
    vif_refs = session.query(models.VirtualInterface).\
                       filter_by(network_id=network_id).\
                       options(joinedload('network')).\
                       options(joinedload('instance')).\
                       options(joinedload('fixed_ips')).\
                       all()
    return vif_refs


@require_context
def virtual_interface_delete(context, vif_id):
    """Delete virtual interface record from teh database.

    :param vif_id: = id of vif to delete
    """
    session = get_session()
    vif_ref = virtual_interface_get(context, vif_id, session)
    with session.begin():
        session.delete(vif_ref)


@require_context
def virtual_interface_delete_by_instance(context, instance_id):
    """Delete virtual interface records that are associated
    with the instance given by instance_id.

    :param instance_id: = id of instance
    """
    vif_refs = virtual_interface_get_by_instance(context, instance_id)
    for vif_ref in vif_refs:
        virtual_interface_delete(context, vif_ref['id'])


###################


def _metadata_refs(metadata_dict, meta_class):
    metadata_refs = []
    if metadata_dict:
        for k, v in metadata_dict.iteritems():
            metadata_ref = meta_class()
            metadata_ref['key'] = k
            metadata_ref['value'] = v
            metadata_refs.append(metadata_ref)
    return metadata_refs


@require_context
def instance_create(context, values):
    """Create a new Instance record in the database.

    context - request context object
    values - dict containing column values.
    """
    values['metadata'] = _metadata_refs(values.get('metadata'),
                                        models.InstanceMetadata)
    instance_ref = models.Instance()
    instance_ref['uuid'] = str(utils.gen_uuid())

    instance_ref.update(values)

    session = get_session()
    with session.begin():
        instance_ref.save(session=session)
    return instance_ref


@require_admin_context
def instance_data_get_for_project(context, project_id):
    session = get_session()
    result = session.query(func.count(models.Instance.id),
                           func.sum(models.Instance.vcpus),
                           func.sum(models.Instance.memory_mb)).\
                     filter_by(project_id=project_id).\
                     filter_by(deleted=False).\
                     first()
    # NOTE(vish): convert None to 0
    return (result[0] or 0, result[1] or 0, result[2] or 0)


@require_context
def instance_destroy(context, instance_id):
    session = get_session()
    with session.begin():
        session.query(models.Instance).\
                filter_by(id=instance_id).\
                update({'deleted': True,
                        'deleted_at': utils.utcnow(),
                        'updated_at': literal_column('updated_at')})
        session.query(models.SecurityGroupInstanceAssociation).\
                filter_by(instance_id=instance_id).\
                update({'deleted': True,
                        'deleted_at': utils.utcnow(),
                        'updated_at': literal_column('updated_at')})
        session.query(models.InstanceMetadata).\
                filter_by(instance_id=instance_id).\
                update({'deleted': True,
                        'deleted_at': utils.utcnow(),
                        'updated_at': literal_column('updated_at')})


@require_context
def instance_stop(context, instance_id):
    session = get_session()
    with session.begin():
        session.query(models.Instance).\
                filter_by(id=instance_id).\
                update({'host': None,
                        'vm_state': vm_states.STOPPED,
                        'task_state': None,
                        'updated_at': literal_column('updated_at')})
        session.query(models.SecurityGroupInstanceAssociation).\
                filter_by(instance_id=instance_id).\
                update({'updated_at': literal_column('updated_at')})
        session.query(models.InstanceMetadata).\
                filter_by(instance_id=instance_id).\
                update({'updated_at': literal_column('updated_at')})


@require_context
def instance_get_by_uuid(context, uuid, session=None):
    partial = _build_instance_get(context, session=session)
    result = partial.filter_by(uuid=uuid)
    result = result.first()
    if not result:
        # FIXME(sirp): it would be nice if InstanceNotFound would accept a
        # uuid parameter as well
        raise exception.InstanceNotFound(instance_id=uuid)
    return result


@require_context
def instance_get(context, instance_id, session=None):
    partial = _build_instance_get(context, session=session)
    result = partial.filter_by(id=instance_id)
    result = result.first()
    if not result:
        raise exception.InstanceNotFound(instance_id=instance_id)
    return result


@require_context
def _build_instance_get(context, session=None):
    if not session:
        session = get_session()

    partial = session.query(models.Instance).\
                     options(joinedload_all('fixed_ips.floating_ips')).\
                     options(joinedload_all('fixed_ips.network')).\
                     options(joinedload('virtual_interfaces')).\
                     options(joinedload_all('security_groups.rules')).\
                     options(joinedload('volumes')).\
                     options(joinedload('metadata')).\
                     options(joinedload('instance_type'))

    if is_admin_context(context):
        partial = partial.filter_by(deleted=can_read_deleted(context))
    elif is_user_context(context):
        partial = partial.filter_by(project_id=context.project_id).\
                        filter_by(deleted=False)
    return partial


@require_admin_context
def instance_get_all(context):
    session = get_session()
    return session.query(models.Instance).\
                   options(joinedload_all('fixed_ips.floating_ips')).\
                   options(joinedload_all('virtual_interfaces.network')).\
                   options(joinedload_all(
                           'virtual_interfaces.fixed_ips.floating_ips')).\
                   options(joinedload('virtual_interfaces.instance')).\
                   options(joinedload('security_groups')).\
                   options(joinedload_all('fixed_ips.network')).\
                   options(joinedload('metadata')).\
                   options(joinedload('instance_type')).\
                   filter_by(deleted=can_read_deleted(context)).\
                   all()


@require_context
def instance_get_all_by_filters(context, filters):
    """Return instances that match all filters.  Deleted instances
    will be returned by default, unless there's a filter that says
    otherwise"""

    def _regexp_filter_by_ipv6(instance, filter_re):
        for interface in instance['virtual_interfaces']:
            fixed_ipv6 = interface.get('fixed_ipv6')
            if fixed_ipv6 and filter_re.match(fixed_ipv6):
                return True
        return False

    def _regexp_filter_by_ip(instance, filter_re):
        for interface in instance['virtual_interfaces']:
            for fixed_ip in interface['fixed_ips']:
                if not fixed_ip or not fixed_ip['address']:
                    continue
                if filter_re.match(fixed_ip['address']):
                    return True
                for floating_ip in fixed_ip.get('floating_ips', []):
                    if not floating_ip or not floating_ip['address']:
                        continue
                    if filter_re.match(floating_ip['address']):
                        return True
        return False

    def _regexp_filter_by_metadata(instance, meta):
        inst_metadata = [{node['key']: node['value']} \
                         for node in instance['metadata']]
        if isinstance(meta, list):
            for node in meta:
                if node not in inst_metadata:
                    return False
        elif isinstance(meta, dict):
            for k, v in meta.iteritems():
                if {k: v} not in inst_metadata:
                    return False
        return True

    def _regexp_filter_by_column(instance, filter_name, filter_re):
        try:
            v = getattr(instance, filter_name)
        except AttributeError:
            return True
        if v and filter_re.match(str(v)):
            return True
        return False

    def _exact_match_filter(query, column, value):
        """Do exact match against a column.  value to match can be a list
        so you can match any value in the list.
        """
        if isinstance(value, list):
            column_attr = getattr(models.Instance, column)
            return query.filter(column_attr.in_(value))
        else:
            filter_dict = {}
            filter_dict[column] = value
            return query.filter_by(**filter_dict)

    session = get_session()
    query_prefix = session.query(models.Instance).\
                   options(joinedload_all('fixed_ips.floating_ips')).\
                   options(joinedload_all('virtual_interfaces.network')).\
                   options(joinedload_all(
                           'virtual_interfaces.fixed_ips.floating_ips')).\
                   options(joinedload('virtual_interfaces.instance')).\
                   options(joinedload('security_groups')).\
                   options(joinedload_all('fixed_ips.network')).\
                   options(joinedload('metadata')).\
                   options(joinedload('instance_type')).\
                   order_by(desc(models.Instance.created_at))

    # Make a copy of the filters dictionary to use going forward, as we'll
    # be modifying it and we shouldn't affect the caller's use of it.
    filters = filters.copy()

    if 'changes-since' in filters:
        changes_since = filters['changes-since']
        query_prefix = query_prefix.\
                            filter(models.Instance.updated_at > changes_since)

    if not context.is_admin:
        # If we're not admin context, add appropriate filter..
        if context.project_id:
            filters['project_id'] = context.project_id
        else:
            filters['user_id'] = context.user_id

    # Filters for exact matches that we can do along with the SQL query...
    # For other filters that don't match this, we will do regexp matching
    exact_match_filter_names = ['project_id', 'user_id', 'image_ref',
            'vm_state', 'instance_type_id', 'deleted']

    query_filters = [key for key in filters.iterkeys()
            if key in exact_match_filter_names]

    for filter_name in query_filters:
        # Do the matching and remove the filter from the dictionary
        # so we don't try it again below..
        query_prefix = _exact_match_filter(query_prefix, filter_name,
                filters.pop(filter_name))

    instances = query_prefix.all()

    if not instances:
        return []

    # Now filter on everything else for regexp matching..
    # For filters not in the list, we'll attempt to use the filter_name
    # as a column name in Instance..
    regexp_filter_funcs = {'ip6': _regexp_filter_by_ipv6,
            'ip': _regexp_filter_by_ip}

    for filter_name in filters.iterkeys():
        filter_func = regexp_filter_funcs.get(filter_name, None)
        filter_re = re.compile(str(filters[filter_name]))
        if filter_func:
            filter_l = lambda instance: filter_func(instance, filter_re)
        elif filter_name == 'metadata':
            filter_l = lambda instance: _regexp_filter_by_metadata(instance,
                    filters[filter_name])
        else:
            filter_l = lambda instance: _regexp_filter_by_column(instance,
                    filter_name, filter_re)
        instances = filter(filter_l, instances)

    return instances


@require_context
def instance_get_active_by_window(context, begin, end=None, project_id=None):
    """Return instances that were continuously active over window."""
    session = get_session()
    query = session.query(models.Instance).\
                    filter(models.Instance.launched_at < begin)
    if end:
        query = query.filter(or_(models.Instance.terminated_at == None,
                                 models.Instance.terminated_at > end))
    else:
        query = query.filter(models.Instance.terminated_at == None)
    if project_id:
        query = query.filter_by(project_id=project_id)
    return query.all()


@require_admin_context
def instance_get_active_by_window_joined(context, begin, end=None,
                                         project_id=None):
    """Return instances and joins that were continuously active over window."""
    session = get_session()
    query = session.query(models.Instance).\
                    options(joinedload_all('fixed_ips.floating_ips')).\
                    options(joinedload('security_groups')).\
                    options(joinedload_all('fixed_ips.network')).\
                    options(joinedload('instance_type')).\
                    filter(models.Instance.launched_at < begin)
    if end:
        query = query.filter(or_(models.Instance.terminated_at == None,
                                 models.Instance.terminated_at > end))
    else:
        query = query.filter(models.Instance.terminated_at == None)
    if project_id:
        query = query.filter_by(project_id=project_id)
    return query.all()


@require_admin_context
def instance_get_all_by_user(context, user_id):
    session = get_session()
    return session.query(models.Instance).\
                   options(joinedload_all('fixed_ips.floating_ips')).\
                   options(joinedload('virtual_interfaces')).\
                   options(joinedload('security_groups')).\
                   options(joinedload_all('fixed_ips.network')).\
                   options(joinedload('metadata')).\
                   options(joinedload('instance_type')).\
                   filter_by(deleted=can_read_deleted(context)).\
                   filter_by(user_id=user_id).\
                   all()


@require_admin_context
def instance_get_all_by_host(context, host):
    session = get_session()
    return session.query(models.Instance).\
                   options(joinedload_all('fixed_ips.floating_ips')).\
                   options(joinedload('virtual_interfaces')).\
                   options(joinedload('security_groups')).\
                   options(joinedload_all('fixed_ips.network')).\
                   options(joinedload('metadata')).\
                   options(joinedload('instance_type')).\
                   filter_by(host=host).\
                   filter_by(deleted=can_read_deleted(context)).\
                   all()


@require_context
def instance_get_all_by_project(context, project_id):
    authorize_project_context(context, project_id)

    session = get_session()
    return session.query(models.Instance).\
                   options(joinedload_all('fixed_ips.floating_ips')).\
                   options(joinedload('virtual_interfaces')).\
                   options(joinedload('security_groups')).\
                   options(joinedload_all('fixed_ips.network')).\
                   options(joinedload('metadata')).\
                   options(joinedload('instance_type')).\
                   filter_by(project_id=project_id).\
                   filter_by(deleted=can_read_deleted(context)).\
                   all()


@require_context
def instance_get_all_by_reservation(context, reservation_id):
    session = get_session()
    query = session.query(models.Instance).\
                    filter_by(reservation_id=reservation_id).\
                    options(joinedload_all('fixed_ips.floating_ips')).\
                    options(joinedload('virtual_interfaces')).\
                    options(joinedload('security_groups')).\
                    options(joinedload_all('fixed_ips.network')).\
                    options(joinedload('metadata')).\
                    options(joinedload('instance_type'))

    if is_admin_context(context):
        return query.\
                filter_by(deleted=can_read_deleted(context)).\
                all()
    elif is_user_context(context):
        return query.\
                filter_by(project_id=context.project_id).\
                filter_by(deleted=False).\
                all()


@require_context
def instance_get_by_fixed_ip(context, address):
    """Return instance ref by exact match of FixedIP"""
    fixed_ip_ref = fixed_ip_get_by_address(context, address)
    return fixed_ip_ref.instance


@require_context
def instance_get_by_fixed_ipv6(context, address):
    """Return instance ref by exact match of IPv6"""
    session = get_session()

    # convert IPv6 address to mac
    mac = ipv6.to_mac(address)

    # get virtual interface
    vif_ref = virtual_interface_get_by_address(context, mac)

    # look up instance based on instance_id from vif row
    result = session.query(models.Instance).\
                     filter_by(id=vif_ref['instance_id'])
    return result


@require_admin_context
def instance_get_project_vpn(context, project_id):
    session = get_session()
    return session.query(models.Instance).\
                   options(joinedload_all('fixed_ips.floating_ips')).\
                   options(joinedload('virtual_interfaces')).\
                   options(joinedload('security_groups')).\
                   options(joinedload_all('fixed_ips.network')).\
                   options(joinedload('metadata')).\
                   options(joinedload('instance_type')).\
                   filter_by(project_id=project_id).\
                   filter_by(image_ref=str(FLAGS.vpn_image_id)).\
                   filter_by(deleted=can_read_deleted(context)).\
                   first()


@require_context
def instance_get_fixed_addresses(context, instance_id):
    session = get_session()
    with session.begin():
        instance_ref = instance_get(context, instance_id, session=session)
        try:
            fixed_ips = fixed_ip_get_by_instance(context, instance_id)
        except exception.NotFound:
            return []
        return [fixed_ip.address for fixed_ip in fixed_ips]


@require_context
def instance_get_fixed_addresses_v6(context, instance_id):
    session = get_session()
    with session.begin():
        # get instance
        instance_ref = instance_get(context, instance_id, session=session)
        # assume instance has 1 mac for each network associated with it
        # get networks associated with instance
        network_refs = network_get_all_by_instance(context, instance_id)
        # compile a list of cidr_v6 prefixes sorted by network id
        prefixes = [ref.cidr_v6 for ref in
                sorted(network_refs, key=lambda ref: ref.id)]
        # get vifs associated with instance
        vif_refs = virtual_interface_get_by_instance(context, instance_ref.id)
        # compile list of the mac_addresses for vifs sorted by network id
        macs = [vif_ref['address'] for vif_ref in
                sorted(vif_refs, key=lambda vif_ref: vif_ref['network_id'])]
        # get project id from instance
        project_id = instance_ref.project_id
        # combine prefixes, macs, and project_id into (prefix,mac,p_id) tuples
        prefix_mac_tuples = zip(prefixes, macs, [project_id for m in macs])
        # return list containing ipv6 address for each tuple
        return [ipv6.to_global(*t) for t in prefix_mac_tuples]


@require_context
def instance_get_floating_address(context, instance_id):
    fixed_ip_refs = fixed_ip_get_by_instance(context, instance_id)
    if not fixed_ip_refs:
        return None
    # NOTE(tr3buchet): this only gets the first fixed_ip
    # won't find floating ips associated with other fixed_ips
    if not fixed_ip_refs[0].floating_ips:
        return None
    # NOTE(vish): this just returns the first floating ip
    return fixed_ip_refs[0].floating_ips[0]['address']


@require_context
def instance_update(context, instance_id, values):
    session = get_session()
    metadata = values.get('metadata')
    if metadata is not None:
        instance_metadata_update(context,
                                 instance_id,
                                 values.pop('metadata'),
                                 delete=True)
    with session.begin():
        if utils.is_uuid_like(instance_id):
            instance_ref = instance_get_by_uuid(context, instance_id,
                                                session=session)
        else:
            instance_ref = instance_get(context, instance_id, session=session)
        instance_ref.update(values)
        instance_ref.save(session=session)
        return instance_ref


def instance_add_security_group(context, instance_id, security_group_id):
    """Associate the given security group with the given instance"""
    session = get_session()
    with session.begin():
        instance_ref = instance_get(context, instance_id, session=session)
        security_group_ref = security_group_get(context,
                                                security_group_id,
                                                session=session)
        instance_ref.security_groups += [security_group_ref]
        instance_ref.save(session=session)


@require_context
def instance_remove_security_group(context, instance_id, security_group_id):
    """Disassociate the given security group from the given instance"""
    session = get_session()

    session.query(models.SecurityGroupInstanceAssociation).\
                filter_by(instance_id=instance_id).\
                filter_by(security_group_id=security_group_id).\
                update({'deleted': True,
                        'deleted_at': utils.utcnow(),
                        'updated_at': literal_column('updated_at')})


@require_context
def instance_action_create(context, values):
    """Create an instance action from the values dictionary."""
    action_ref = models.InstanceActions()
    action_ref.update(values)

    session = get_session()
    with session.begin():
        action_ref.save(session=session)
    return action_ref


@require_admin_context
def instance_get_actions(context, instance_id):
    """Return the actions associated to the given instance id"""
    session = get_session()

    if utils.is_uuid_like(instance_id):
        instance = instance_get_by_uuid(context, instance_id, session)
        instance_id = instance.id

    return session.query(models.InstanceActions).\
        filter_by(instance_id=instance_id).\
       all()


###################


@require_context
def key_pair_create(context, values):
    key_pair_ref = models.KeyPair()
    key_pair_ref.update(values)
    key_pair_ref.save()
    return key_pair_ref


@require_context
def key_pair_destroy(context, user_id, name):
    authorize_user_context(context, user_id)
    session = get_session()
    with session.begin():
        key_pair_ref = key_pair_get(context, user_id, name, session=session)
        key_pair_ref.delete(session=session)


@require_context
def key_pair_destroy_all_by_user(context, user_id):
    authorize_user_context(context, user_id)
    session = get_session()
    with session.begin():
        session.query(models.KeyPair).\
                filter_by(user_id=user_id).\
                update({'deleted': True,
                        'deleted_at': utils.utcnow(),
                        'updated_at': literal_column('updated_at')})


@require_context
def key_pair_get(context, user_id, name, session=None):
    authorize_user_context(context, user_id)

    if not session:
        session = get_session()

    result = session.query(models.KeyPair).\
                     filter_by(user_id=user_id).\
                     filter_by(name=name).\
                     filter_by(deleted=can_read_deleted(context)).\
                     first()
    if not result:
        raise exception.KeypairNotFound(user_id=user_id, name=name)
    return result


@require_context
def key_pair_get_all_by_user(context, user_id):
    authorize_user_context(context, user_id)
    session = get_session()
    return session.query(models.KeyPair).\
                   filter_by(user_id=user_id).\
                   filter_by(deleted=False).\
                   all()


###################


@require_admin_context
def network_associate(context, project_id, force=False):
    """Associate a project with a network.

    called by project_get_networks under certain conditions
    and network manager add_network_to_project()

    only associate if the project doesn't already have a network
    or if force is True

    force solves race condition where a fresh project has multiple instance
    builds simultaneosly picked up by multiple network hosts which attempt
    to associate the project with multiple networks
    force should only be used as a direct consequence of user request
    all automated requests should not use force
    """
    session = get_session()
    with session.begin():

        def network_query(project_filter):
            return session.query(models.Network).\
                           filter_by(deleted=False).\
                           filter_by(project_id=project_filter).\
                           with_lockmode('update').\
                           first()

        if not force:
            # find out if project has a network
            network_ref = network_query(project_id)

        if force or not network_ref:
            # in force mode or project doesn't have a network so assocaite
            # with a new network

            # get new network
            network_ref = network_query(None)
            if not network_ref:
                raise db.NoMoreNetworks()

            # associate with network
            # NOTE(vish): if with_lockmode isn't supported, as in sqlite,
            #             then this has concurrency issues
            network_ref['project_id'] = project_id
            session.add(network_ref)
    return network_ref


@require_admin_context
def network_count(context):
    session = get_session()
    return session.query(models.Network).\
                   filter_by(deleted=can_read_deleted(context)).\
                   count()


@require_admin_context
def network_count_allocated_ips(context, network_id):
    session = get_session()
    return session.query(models.FixedIp).\
                   filter_by(network_id=network_id).\
                   filter_by(allocated=True).\
                   filter_by(deleted=False).\
                   count()


@require_admin_context
def network_count_available_ips(context, network_id):
    session = get_session()
    return session.query(models.FixedIp).\
                   filter_by(network_id=network_id).\
                   filter_by(allocated=False).\
                   filter_by(reserved=False).\
                   filter_by(deleted=False).\
                   count()


@require_admin_context
def network_count_reserved_ips(context, network_id):
    session = get_session()
    return session.query(models.FixedIp).\
                   filter_by(network_id=network_id).\
                   filter_by(reserved=True).\
                   filter_by(deleted=False).\
                   count()


@require_admin_context
def network_create_safe(context, values):
    network_ref = models.Network()
    network_ref.update(values)
    try:
        network_ref.save()
        return network_ref
    except IntegrityError:
        return None


@require_admin_context
def network_delete_safe(context, network_id):
    session = get_session()
    with session.begin():
        network_ref = network_get(context, network_id=network_id, \
                                  session=session)
        session.delete(network_ref)


@require_admin_context
def network_disassociate(context, network_id):
    network_update(context, network_id, {'project_id': None,
                                         'host': None})


@require_admin_context
def network_disassociate_all(context):
    session = get_session()
    session.query(models.Network).\
            update({'project_id': None,
                    'updated_at': literal_column('updated_at')})


@require_context
def network_get(context, network_id, session=None):
    if not session:
        session = get_session()
    result = None

    if is_admin_context(context):
        result = session.query(models.Network).\
                         filter_by(id=network_id).\
                         filter_by(deleted=can_read_deleted(context)).\
                         first()
    elif is_user_context(context):
        result = session.query(models.Network).\
                         filter_by(project_id=context.project_id).\
                         filter_by(id=network_id).\
                         filter_by(deleted=False).\
                         first()
    if not result:
        raise exception.NetworkNotFound(network_id=network_id)

    return result


@require_admin_context
def network_get_all(context):
    session = get_session()
    result = session.query(models.Network).\
                 filter_by(deleted=False).all()
    if not result:
        raise exception.NoNetworksFound()
    return result


@require_admin_context
def network_get_all_by_uuids(context, network_uuids, project_id=None):
    session = get_session()
    project_or_none = or_(models.Network.project_id == project_id,
                              models.Network.project_id == None)
    result = session.query(models.Network).\
                 filter(models.Network.uuid.in_(network_uuids)).\
                 filter(project_or_none).\
                 filter_by(deleted=False).all()
    if not result:
        raise exception.NoNetworksFound()

    #check if host is set to all of the networks
    # returned in the result
    for network in result:
            if network['host'] is None:
                raise exception.NetworkHostNotSet(network_id=network['id'])

    #check if the result contains all the networks
    #we are looking for
    for network_uuid in network_uuids:
        found = False
        for network in result:
            if network['uuid'] == network_uuid:
                found = True
                break
        if not found:
            if project_id:
                raise exception.NetworkNotFoundForProject(network_uuid=uuid,
                                              project_id=context.project_id)
            raise exception.NetworkNotFound(network_id=network_uuid)

    return result

# NOTE(vish): pylint complains because of the long method name, but
#             it fits with the names of the rest of the methods
# pylint: disable=C0103


@require_admin_context
def network_get_associated_fixed_ips(context, network_id):
    session = get_session()
    return session.query(models.FixedIp).\
                   options(joinedload_all('instance')).\
                   filter_by(network_id=network_id).\
                   filter(models.FixedIp.instance_id != None).\
                   filter(models.FixedIp.virtual_interface_id != None).\
                   filter_by(deleted=False).\
                   all()


@require_admin_context
def network_get_by_bridge(context, bridge):
    session = get_session()
    result = session.query(models.Network).\
                 filter_by(bridge=bridge).\
                 filter_by(deleted=False).\
                 first()

    if not result:
        raise exception.NetworkNotFoundForBridge(bridge=bridge)
    return result


@require_admin_context
def network_get_by_uuid(context, uuid):
    session = get_session()
    result = session.query(models.Network).\
                 filter_by(uuid=uuid).\
                 filter_by(deleted=False).\
                 first()

    if not result:
        raise exception.NetworkNotFoundForUUID(uuid=uuid)
    return result


@require_admin_context
def network_get_by_cidr(context, cidr):
    session = get_session()
    result = session.query(models.Network).\
                filter(or_(models.Network.cidr == cidr,
                           models.Network.cidr_v6 == cidr)).\
                filter_by(deleted=False).\
                first()

    if not result:
        raise exception.NetworkNotFoundForCidr(cidr=cidr)
    return result


@require_admin_context
def network_get_by_instance(_context, instance_id):
    # note this uses fixed IP to get to instance
    # only works for networks the instance has an IP from
    session = get_session()
    rv = session.query(models.Network).\
                 filter_by(deleted=False).\
                 join(models.Network.fixed_ips).\
                 filter_by(instance_id=instance_id).\
                 filter_by(deleted=False).\
                 first()
    if not rv:
        raise exception.NetworkNotFoundForInstance(instance_id=instance_id)
    return rv


@require_admin_context
def network_get_all_by_instance(_context, instance_id):
    session = get_session()
    rv = session.query(models.Network).\
                 filter_by(deleted=False).\
                 join(models.Network.fixed_ips).\
                 filter_by(instance_id=instance_id).\
                 filter_by(deleted=False).\
                 all()
    if not rv:
        raise exception.NetworkNotFoundForInstance(instance_id=instance_id)
    return rv


@require_admin_context
def network_get_all_by_host(context, host):
    session = get_session()
    with session.begin():
        # NOTE(vish): return networks that have host set
        #             or that have a fixed ip with host set
        host_filter = or_(models.Network.host == host,
                          models.FixedIp.host == host)

        return session.query(models.Network).\
                       filter_by(deleted=False).\
                       join(models.Network.fixed_ips).\
                       filter(host_filter).\
                       filter_by(deleted=False).\
                       all()


@require_admin_context
def network_set_host(context, network_id, host_id):
    session = get_session()
    with session.begin():
        network_ref = session.query(models.Network).\
                              filter_by(id=network_id).\
                              filter_by(deleted=False).\
                              with_lockmode('update').\
                              first()
        if not network_ref:
            raise exception.NetworkNotFound(network_id=network_id)

        # NOTE(vish): if with_lockmode isn't supported, as in sqlite,
        #             then this has concurrency issues
        if not network_ref['host']:
            network_ref['host'] = host_id
            session.add(network_ref)

    return network_ref['host']


@require_context
def network_update(context, network_id, values):
    session = get_session()
    with session.begin():
        network_ref = network_get(context, network_id, session=session)
        network_ref.update(values)
        network_ref.save(session=session)
        return network_ref


###################


def queue_get_for(_context, topic, physical_node_id):
    # FIXME(ja): this should be servername?
    return "%s.%s" % (topic, physical_node_id)


###################


@require_admin_context
def export_device_count(context):
    session = get_session()
    return session.query(models.ExportDevice).\
                   filter_by(deleted=can_read_deleted(context)).\
                   count()


@require_admin_context
def export_device_create_safe(context, values):
    export_device_ref = models.ExportDevice()
    export_device_ref.update(values)
    try:
        export_device_ref.save()
        return export_device_ref
    except IntegrityError:
        return None


###################


@require_admin_context
def iscsi_target_count_by_host(context, host):
    session = get_session()
    return session.query(models.IscsiTarget).\
                   filter_by(deleted=can_read_deleted(context)).\
                   filter_by(host=host).\
                   count()


@require_admin_context
def iscsi_target_create_safe(context, values):
    iscsi_target_ref = models.IscsiTarget()
    for (key, value) in values.iteritems():
        iscsi_target_ref[key] = value
    try:
        iscsi_target_ref.save()
        return iscsi_target_ref
    except IntegrityError:
        return None


###################


@require_admin_context
def auth_token_destroy(context, token_id):
    session = get_session()
    with session.begin():
        token_ref = auth_token_get(context, token_id, session=session)
        token_ref.delete(session=session)


@require_admin_context
def auth_token_get(context, token_hash, session=None):
    if session is None:
        session = get_session()
    tk = session.query(models.AuthToken).\
                  filter_by(token_hash=token_hash).\
                  filter_by(deleted=can_read_deleted(context)).\
                  first()
    if not tk:
        raise exception.AuthTokenNotFound(token=token_hash)
    return tk


@require_admin_context
def auth_token_update(context, token_hash, values):
    session = get_session()
    with session.begin():
        token_ref = auth_token_get(context, token_hash, session=session)
        token_ref.update(values)
        token_ref.save(session=session)


@require_admin_context
def auth_token_create(_context, token):
    tk = models.AuthToken()
    tk.update(token)
    tk.save()
    return tk


###################


@require_context
def quota_get(context, project_id, resource, session=None):
    if not session:
        session = get_session()
    result = session.query(models.Quota).\
                     filter_by(project_id=project_id).\
                     filter_by(resource=resource).\
                     filter_by(deleted=False).\
                     first()
    if not result:
        raise exception.ProjectQuotaNotFound(project_id=project_id)
    return result


@require_context
def quota_get_all_by_project(context, project_id):
    authorize_project_context(context, project_id)
    session = get_session()
    result = {'project_id': project_id}
    rows = session.query(models.Quota).\
                   filter_by(project_id=project_id).\
                   filter_by(deleted=False).\
                   all()
    for row in rows:
        result[row.resource] = row.hard_limit
    return result


@require_admin_context
def quota_create(context, project_id, resource, limit):
    quota_ref = models.Quota()
    quota_ref.project_id = project_id
    quota_ref.resource = resource
    quota_ref.hard_limit = limit
    quota_ref.save()
    return quota_ref


@require_admin_context
def quota_update(context, project_id, resource, limit):
    session = get_session()
    with session.begin():
        quota_ref = quota_get(context, project_id, resource, session=session)
        quota_ref.hard_limit = limit
        quota_ref.save(session=session)


@require_admin_context
def quota_destroy(context, project_id, resource):
    session = get_session()
    with session.begin():
        quota_ref = quota_get(context, project_id, resource, session=session)
        quota_ref.delete(session=session)


@require_admin_context
def quota_destroy_all_by_project(context, project_id):
    session = get_session()
    with session.begin():
        quotas = session.query(models.Quota).\
                         filter_by(project_id=project_id).\
                         filter_by(deleted=False).\
                         all()
        for quota_ref in quotas:
            quota_ref.delete(session=session)


###################


@require_admin_context
def volume_allocate_shelf_and_blade(context, volume_id):
    session = get_session()
    with session.begin():
        export_device = session.query(models.ExportDevice).\
                                filter_by(volume=None).\
                                filter_by(deleted=False).\
                                with_lockmode('update').\
                                first()
        # NOTE(vish): if with_lockmode isn't supported, as in sqlite,
        #             then this has concurrency issues
        if not export_device:
            raise db.NoMoreBlades()
        export_device.volume_id = volume_id
        session.add(export_device)
    return (export_device.shelf_id, export_device.blade_id)


@require_admin_context
def volume_allocate_iscsi_target(context, volume_id, host):
    session = get_session()
    with session.begin():
        iscsi_target_ref = session.query(models.IscsiTarget).\
                                filter_by(volume=None).\
                                filter_by(host=host).\
                                filter_by(deleted=False).\
                                with_lockmode('update').\
                                first()
        # NOTE(vish): if with_lockmode isn't supported, as in sqlite,
        #             then this has concurrency issues
        if not iscsi_target_ref:
            raise db.NoMoreTargets()
        iscsi_target_ref.volume_id = volume_id
        session.add(iscsi_target_ref)
    return iscsi_target_ref.target_num


@require_admin_context
def volume_attached(context, volume_id, instance_id, mountpoint):
    session = get_session()
    with session.begin():
        volume_ref = volume_get(context, volume_id, session=session)
        volume_ref['status'] = 'in-use'
        volume_ref['mountpoint'] = mountpoint
        volume_ref['attach_status'] = 'attached'
        volume_ref.instance = instance_get(context, instance_id,
                                           session=session)
        volume_ref.save(session=session)


@require_context
def volume_create(context, values):
    values['volume_metadata'] = _metadata_refs(values.get('metadata'),
                                               models.VolumeMetadata)
    volume_ref = models.Volume()
    volume_ref.update(values)

    session = get_session()
    with session.begin():
        volume_ref.save(session=session)
    return volume_ref


@require_admin_context
def volume_data_get_for_project(context, project_id):
    session = get_session()
    result = session.query(func.count(models.Volume.id),
                           func.sum(models.Volume.size)).\
                     filter_by(project_id=project_id).\
                     filter_by(deleted=False).\
                     first()
    # NOTE(vish): convert None to 0
    return (result[0] or 0, result[1] or 0)


@require_admin_context
def volume_destroy(context, volume_id):
    session = get_session()
    with session.begin():
        session.query(models.Volume).\
                filter_by(id=volume_id).\
                update({'deleted': True,
                        'deleted_at': utils.utcnow(),
                        'updated_at': literal_column('updated_at')})
        session.query(models.ExportDevice).\
                filter_by(volume_id=volume_id).\
                update({'volume_id': None})
        session.query(models.IscsiTarget).\
                filter_by(volume_id=volume_id).\
                update({'volume_id': None})
        session.query(models.VolumeMetadata).\
                filter_by(volume_id=volume_id).\
                update({'deleted': True,
                        'deleted_at': utils.utcnow(),
                        'updated_at': literal_column('updated_at')})


@require_admin_context
def volume_detached(context, volume_id):
    session = get_session()
    with session.begin():
        volume_ref = volume_get(context, volume_id, session=session)
        volume_ref['status'] = 'available'
        volume_ref['mountpoint'] = None
        volume_ref['attach_status'] = 'detached'
        volume_ref.instance = None
        volume_ref.save(session=session)


@require_context
def volume_get(context, volume_id, session=None):
    if not session:
        session = get_session()
    result = None

    if is_admin_context(context):
        result = session.query(models.Volume).\
                         options(joinedload('instance')).\
                         options(joinedload('volume_metadata')).\
                         options(joinedload('volume_type')).\
                         filter_by(id=volume_id).\
                         filter_by(deleted=can_read_deleted(context)).\
                         first()
    elif is_user_context(context):
        result = session.query(models.Volume).\
                         options(joinedload('instance')).\
                         options(joinedload('volume_metadata')).\
                         options(joinedload('volume_type')).\
                         filter_by(project_id=context.project_id).\
                         filter_by(id=volume_id).\
                         filter_by(deleted=False).\
                         first()
    if not result:
        raise exception.VolumeNotFound(volume_id=volume_id)

    return result


@require_admin_context
def volume_get_all(context):
    session = get_session()
    return session.query(models.Volume).\
                   options(joinedload('instance')).\
                   options(joinedload('volume_metadata')).\
                   options(joinedload('volume_type')).\
                   filter_by(deleted=can_read_deleted(context)).\
                   all()


@require_admin_context
def volume_get_all_by_host(context, host):
    session = get_session()
    return session.query(models.Volume).\
                   options(joinedload('instance')).\
                   options(joinedload('volume_metadata')).\
                   options(joinedload('volume_type')).\
                   filter_by(host=host).\
                   filter_by(deleted=can_read_deleted(context)).\
                   all()


@require_admin_context
def volume_get_all_by_instance(context, instance_id):
    session = get_session()
    result = session.query(models.Volume).\
                     options(joinedload('volume_metadata')).\
                     options(joinedload('volume_type')).\
                     filter_by(instance_id=instance_id).\
                     filter_by(deleted=False).\
                     all()
    if not result:
        raise exception.VolumeNotFoundForInstance(instance_id=instance_id)
    return result


@require_context
def volume_get_all_by_project(context, project_id):
    authorize_project_context(context, project_id)

    session = get_session()
    return session.query(models.Volume).\
                   options(joinedload('instance')).\
                   options(joinedload('volume_metadata')).\
                   options(joinedload('volume_type')).\
                   filter_by(project_id=project_id).\
                   filter_by(deleted=can_read_deleted(context)).\
                   all()


@require_admin_context
def volume_get_instance(context, volume_id):
    session = get_session()
    result = session.query(models.Volume).\
                     filter_by(id=volume_id).\
                     filter_by(deleted=can_read_deleted(context)).\
                     options(joinedload('instance')).\
                     options(joinedload('volume_metadata')).\
                     options(joinedload('volume_type')).\
                     first()
    if not result:
        raise exception.VolumeNotFound(volume_id=volume_id)

    return result.instance


@require_admin_context
def volume_get_shelf_and_blade(context, volume_id):
    session = get_session()
    result = session.query(models.ExportDevice).\
                     filter_by(volume_id=volume_id).\
                     first()
    if not result:
        raise exception.ExportDeviceNotFoundForVolume(volume_id=volume_id)

    return (result.shelf_id, result.blade_id)


@require_admin_context
def volume_get_iscsi_target_num(context, volume_id):
    session = get_session()
    result = session.query(models.IscsiTarget).\
                     filter_by(volume_id=volume_id).\
                     first()
    if not result:
        raise exception.ISCSITargetNotFoundForVolume(volume_id=volume_id)

    return result.target_num


@require_context
def volume_update(context, volume_id, values):
    session = get_session()
    metadata = values.get('metadata')
    if metadata is not None:
        volume_metadata_update(context,
                                volume_id,
                                values.pop('metadata'),
                                delete=True)
    with session.begin():
        volume_ref = volume_get(context, volume_id, session=session)
        volume_ref.update(values)
        volume_ref.save(session=session)


####################


@require_context
@require_volume_exists
def volume_metadata_get(context, volume_id):
    session = get_session()

    meta_results = session.query(models.VolumeMetadata).\
                    filter_by(volume_id=volume_id).\
                    filter_by(deleted=False).\
                    all()

    meta_dict = {}
    for i in meta_results:
        meta_dict[i['key']] = i['value']
    return meta_dict


@require_context
@require_volume_exists
def volume_metadata_delete(context, volume_id, key):
    session = get_session()
    session.query(models.VolumeMetadata).\
        filter_by(volume_id=volume_id).\
        filter_by(key=key).\
        filter_by(deleted=False).\
        update({'deleted': True,
                'deleted_at': utils.utcnow(),
                'updated_at': literal_column('updated_at')})


@require_context
@require_volume_exists
def volume_metadata_delete_all(context, volume_id):
    session = get_session()
    session.query(models.VolumeMetadata).\
        filter_by(volume_id=volume_id).\
        filter_by(deleted=False).\
        update({'deleted': True,
                'deleted_at': utils.utcnow(),
                'updated_at': literal_column('updated_at')})


@require_context
@require_volume_exists
def volume_metadata_get_item(context, volume_id, key, session=None):
    if not session:
        session = get_session()

    meta_result = session.query(models.VolumeMetadata).\
                    filter_by(volume_id=volume_id).\
                    filter_by(key=key).\
                    filter_by(deleted=False).\
                    first()

    if not meta_result:
        raise exception.VolumeMetadataNotFound(metadata_key=key,
                                               volume_id=volume_id)
    return meta_result


@require_context
@require_volume_exists
def volume_metadata_update(context, volume_id, metadata, delete):
    session = get_session()

    # Set existing metadata to deleted if delete argument is True
    if delete:
        original_metadata = volume_metadata_get(context, volume_id)
        for meta_key, meta_value in original_metadata.iteritems():
            if meta_key not in metadata:
                meta_ref = volume_metadata_get_item(context, volume_id,
                                                    meta_key, session)
                meta_ref.update({'deleted': True})
                meta_ref.save(session=session)

    meta_ref = None

    # Now update all existing items with new values, or create new meta objects
    for meta_key, meta_value in metadata.iteritems():

        # update the value whether it exists or not
        item = {"value": meta_value}

        try:
            meta_ref = volume_metadata_get_item(context, volume_id,
                                                  meta_key, session)
        except exception.VolumeMetadataNotFound, e:
            meta_ref = models.VolumeMetadata()
            item.update({"key": meta_key, "volume_id": volume_id})

        meta_ref.update(item)
        meta_ref.save(session=session)

    return metadata


###################


@require_context
def snapshot_create(context, values):
    snapshot_ref = models.Snapshot()
    snapshot_ref.update(values)

    session = get_session()
    with session.begin():
        snapshot_ref.save(session=session)
    return snapshot_ref


@require_admin_context
def snapshot_destroy(context, snapshot_id):
    session = get_session()
    with session.begin():
        session.query(models.Snapshot).\
                filter_by(id=snapshot_id).\
                update({'deleted': True,
                        'deleted_at': utils.utcnow(),
                        'updated_at': literal_column('updated_at')})


@require_context
def snapshot_get(context, snapshot_id, session=None):
    if not session:
        session = get_session()
    result = None

    if is_admin_context(context):
        result = session.query(models.Snapshot).\
                         filter_by(id=snapshot_id).\
                         filter_by(deleted=can_read_deleted(context)).\
                         first()
    elif is_user_context(context):
        result = session.query(models.Snapshot).\
                         filter_by(project_id=context.project_id).\
                         filter_by(id=snapshot_id).\
                         filter_by(deleted=False).\
                         first()
    if not result:
        raise exception.SnapshotNotFound(snapshot_id=snapshot_id)

    return result


@require_admin_context
def snapshot_get_all(context):
    session = get_session()
    return session.query(models.Snapshot).\
                   filter_by(deleted=can_read_deleted(context)).\
                   all()


@require_context
def snapshot_get_all_by_project(context, project_id):
    authorize_project_context(context, project_id)

    session = get_session()
    return session.query(models.Snapshot).\
                   filter_by(project_id=project_id).\
                   filter_by(deleted=can_read_deleted(context)).\
                   all()


@require_context
def snapshot_update(context, snapshot_id, values):
    session = get_session()
    with session.begin():
        snapshot_ref = snapshot_get(context, snapshot_id, session=session)
        snapshot_ref.update(values)
        snapshot_ref.save(session=session)


###################


@require_context
def block_device_mapping_create(context, values):
    bdm_ref = models.BlockDeviceMapping()
    bdm_ref.update(values)

    session = get_session()
    with session.begin():
        bdm_ref.save(session=session)


@require_context
def block_device_mapping_update(context, bdm_id, values):
    session = get_session()
    with session.begin():
        session.query(models.BlockDeviceMapping).\
                filter_by(id=bdm_id).\
                filter_by(deleted=False).\
                update(values)


@require_context
def block_device_mapping_update_or_create(context, values):
    session = get_session()
    with session.begin():
        result = session.query(models.BlockDeviceMapping).\
                 filter_by(instance_id=values['instance_id']).\
                 filter_by(device_name=values['device_name']).\
                 filter_by(deleted=False).\
                 first()
        if not result:
            bdm_ref = models.BlockDeviceMapping()
            bdm_ref.update(values)
            bdm_ref.save(session=session)
        else:
            result.update(values)

        # NOTE(yamahata): same virtual device name can be specified multiple
        #                 times. So delete the existing ones.
        virtual_name = values['virtual_name']
        if (virtual_name is not None and
            block_device.is_swap_or_ephemeral(virtual_name)):
            session.query(models.BlockDeviceMapping).\
            filter_by(instance_id=values['instance_id']).\
            filter_by(virtual_name=virtual_name).\
            filter(models.BlockDeviceMapping.device_name !=
                   values['device_name']).\
            update({'deleted': True,
                    'deleted_at': utils.utcnow(),
                    'updated_at': literal_column('updated_at')})


@require_context
def block_device_mapping_get_all_by_instance(context, instance_id):
    session = get_session()
    result = session.query(models.BlockDeviceMapping).\
             filter_by(instance_id=instance_id).\
             filter_by(deleted=False).\
             all()
    if not result:
        return []
    return result


@require_context
def block_device_mapping_destroy(context, bdm_id):
    session = get_session()
    with session.begin():
        session.query(models.BlockDeviceMapping).\
                filter_by(id=bdm_id).\
                update({'deleted': True,
                        'deleted_at': utils.utcnow(),
                        'updated_at': literal_column('updated_at')})


@require_context
def block_device_mapping_destroy_by_instance_and_volume(context, instance_id,
                                                        volume_id):
    session = get_session()
    with session.begin():
        session.query(models.BlockDeviceMapping).\
        filter_by(instance_id=instance_id).\
        filter_by(volume_id=volume_id).\
        filter_by(deleted=False).\
        update({'deleted': True,
                'deleted_at': utils.utcnow(),
                'updated_at': literal_column('updated_at')})


###################


@require_context
def security_group_get_all(context):
    session = get_session()
    return session.query(models.SecurityGroup).\
                   filter_by(deleted=can_read_deleted(context)).\
                   options(joinedload_all('rules')).\
                   all()


@require_context
def security_group_get(context, security_group_id, session=None):
    if not session:
        session = get_session()
    if is_admin_context(context):
        result = session.query(models.SecurityGroup).\
                         filter_by(deleted=can_read_deleted(context),).\
                         filter_by(id=security_group_id).\
                         options(joinedload_all('rules')).\
                         options(joinedload_all('instances')).\
                         first()
    else:
        result = session.query(models.SecurityGroup).\
                         filter_by(deleted=False).\
                         filter_by(id=security_group_id).\
                         filter_by(project_id=context.project_id).\
                         options(joinedload_all('rules')).\
                         options(joinedload_all('instances')).\
                         first()
    if not result:
        raise exception.SecurityGroupNotFound(
                security_group_id=security_group_id)
    return result


@require_context
def security_group_get_by_name(context, project_id, group_name):
    session = get_session()
    result = session.query(models.SecurityGroup).\
                        filter_by(project_id=project_id).\
                        filter_by(name=group_name).\
                        filter_by(deleted=False).\
                        options(joinedload_all('rules')).\
                        options(joinedload_all('instances')).\
                        first()
    if not result:
        raise exception.SecurityGroupNotFoundForProject(project_id=project_id,
                                                 security_group_id=group_name)
    return result


@require_context
def security_group_get_by_project(context, project_id):
    session = get_session()
    return session.query(models.SecurityGroup).\
                   filter_by(project_id=project_id).\
                   filter_by(deleted=False).\
                   options(joinedload_all('rules')).\
                   all()


@require_context
def security_group_get_by_instance(context, instance_id):
    session = get_session()
    return session.query(models.SecurityGroup).\
                   filter_by(deleted=False).\
                   options(joinedload_all('rules')).\
                   join(models.SecurityGroup.instances).\
                   filter_by(id=instance_id).\
                   filter_by(deleted=False).\
                   all()


@require_context
def security_group_exists(context, project_id, group_name):
    try:
        group = security_group_get_by_name(context, project_id, group_name)
        return group is not None
    except exception.NotFound:
        return False


@require_context
def security_group_create(context, values):
    security_group_ref = models.SecurityGroup()
    # FIXME(devcamcar): Unless I do this, rules fails with lazy load exception
    # once save() is called.  This will get cleaned up in next orm pass.
    security_group_ref.rules
    security_group_ref.update(values)
    security_group_ref.save()
    return security_group_ref


@require_context
def security_group_destroy(context, security_group_id):
    session = get_session()
    with session.begin():
        session.query(models.SecurityGroup).\
                filter_by(id=security_group_id).\
                update({'deleted': True,
                        'deleted_at': utils.utcnow(),
                        'updated_at': literal_column('updated_at')})
        session.query(models.SecurityGroupInstanceAssociation).\
                filter_by(security_group_id=security_group_id).\
                update({'deleted': True,
                        'deleted_at': utils.utcnow(),
                        'updated_at': literal_column('updated_at')})
        session.query(models.SecurityGroupIngressRule).\
                filter_by(group_id=security_group_id).\
                update({'deleted': True,
                        'deleted_at': utils.utcnow(),
                        'updated_at': literal_column('updated_at')})


@require_context
def security_group_destroy_all(context, session=None):
    if not session:
        session = get_session()
    with session.begin():
        session.query(models.SecurityGroup).\
                update({'deleted': True,
                        'deleted_at': utils.utcnow(),
                        'updated_at': literal_column('updated_at')})
        session.query(models.SecurityGroupIngressRule).\
                update({'deleted': True,
                        'deleted_at': utils.utcnow(),
                        'updated_at': literal_column('updated_at')})


###################


@require_context
def security_group_rule_get(context, security_group_rule_id, session=None):
    if not session:
        session = get_session()
    if is_admin_context(context):
        result = session.query(models.SecurityGroupIngressRule).\
                         filter_by(deleted=can_read_deleted(context)).\
                         filter_by(id=security_group_rule_id).\
                         first()
    else:
        # TODO(vish): Join to group and check for project_id
        result = session.query(models.SecurityGroupIngressRule).\
                         filter_by(deleted=False).\
                         filter_by(id=security_group_rule_id).\
                         first()
    if not result:
        raise exception.SecurityGroupNotFoundForRule(
                                               rule_id=security_group_rule_id)
    return result


@require_context
def security_group_rule_get_by_security_group(context, security_group_id,
                                              session=None):
    if not session:
        session = get_session()
    if is_admin_context(context):
        result = session.query(models.SecurityGroupIngressRule).\
                         filter_by(deleted=can_read_deleted(context)).\
                         filter_by(parent_group_id=security_group_id).\
                         all()
    else:
        # TODO(vish): Join to group and check for project_id
        result = session.query(models.SecurityGroupIngressRule).\
                         filter_by(deleted=False).\
                         filter_by(parent_group_id=security_group_id).\
                         all()
    return result


@require_context
def security_group_rule_get_by_security_group_grantee(context,
                                                      security_group_id,
                                                      session=None):
    if not session:
        session = get_session()
    if is_admin_context(context):
        result = session.query(models.SecurityGroupIngressRule).\
                         filter_by(deleted=can_read_deleted(context)).\
                         filter_by(group_id=security_group_id).\
                         all()
    else:
        result = session.query(models.SecurityGroupIngressRule).\
                         filter_by(deleted=False).\
                         filter_by(group_id=security_group_id).\
                         all()
    return result


@require_context
def security_group_rule_create(context, values):
    security_group_rule_ref = models.SecurityGroupIngressRule()
    security_group_rule_ref.update(values)
    security_group_rule_ref.save()
    return security_group_rule_ref


@require_context
def security_group_rule_destroy(context, security_group_rule_id):
    session = get_session()
    with session.begin():
        security_group_rule = security_group_rule_get(context,
                                                      security_group_rule_id,
                                                      session=session)
        security_group_rule.delete(session=session)


###################


@require_admin_context
def provider_fw_rule_create(context, rule):
    fw_rule_ref = models.ProviderFirewallRule()
    fw_rule_ref.update(rule)
    fw_rule_ref.save()
    return fw_rule_ref


@require_admin_context
def provider_fw_rule_get_all(context):
    session = get_session()
    return session.query(models.ProviderFirewallRule).\
                   filter_by(deleted=can_read_deleted(context)).\
                   all()


@require_admin_context
def provider_fw_rule_get_all_by_cidr(context, cidr):
    session = get_session()
    return session.query(models.ProviderFirewallRule).\
                   filter_by(deleted=can_read_deleted(context)).\
                   filter_by(cidr=cidr).\
                   all()


@require_admin_context
def provider_fw_rule_destroy(context, rule_id):
    session = get_session()
    with session.begin():
        session.query(models.ProviderFirewallRule).\
                filter_by(id=rule_id).\
                update({'deleted': True,
                        'deleted_at': utils.utcnow(),
                        'updated_at': literal_column('updated_at')})


###################


@require_admin_context
def user_get(context, id, session=None):
    if not session:
        session = get_session()

    result = session.query(models.User).\
                     filter_by(id=id).\
                     filter_by(deleted=can_read_deleted(context)).\
                     first()

    if not result:
        raise exception.UserNotFound(user_id=id)

    return result


@require_admin_context
def user_get_by_access_key(context, access_key, session=None):
    if not session:
        session = get_session()

    result = session.query(models.User).\
                   filter_by(access_key=access_key).\
                   filter_by(deleted=can_read_deleted(context)).\
                   first()

    if not result:
        raise exception.AccessKeyNotFound(access_key=access_key)

    return result


@require_admin_context
def user_create(_context, values):
    user_ref = models.User()
    user_ref.update(values)
    user_ref.save()
    return user_ref


@require_admin_context
def user_delete(context, id):
    session = get_session()
    with session.begin():
        session.query(models.UserProjectAssociation).\
                filter_by(user_id=id).\
                delete()
        session.query(models.UserRoleAssociation).\
                filter_by(user_id=id).\
                delete()
        session.query(models.UserProjectRoleAssociation).\
                filter_by(user_id=id).\
                delete()
        user_ref = user_get(context, id, session=session)
        session.delete(user_ref)


def user_get_all(context):
    session = get_session()
    return session.query(models.User).\
                   filter_by(deleted=can_read_deleted(context)).\
                   all()


def user_get_roles(context, user_id):
    session = get_session()
    with session.begin():
        user_ref = user_get(context, user_id, session=session)
        return [role.role for role in user_ref['roles']]


def user_get_roles_for_project(context, user_id, project_id):
    session = get_session()
    with session.begin():
        res = session.query(models.UserProjectRoleAssociation).\
                   filter_by(user_id=user_id).\
                   filter_by(project_id=project_id).\
                   all()
        return [association.role for association in res]


def user_remove_project_role(context, user_id, project_id, role):
    session = get_session()
    with session.begin():
        session.query(models.UserProjectRoleAssociation).\
                filter_by(user_id=user_id).\
                filter_by(project_id=project_id).\
                filter_by(role=role).\
                delete()


def user_remove_role(context, user_id, role):
    session = get_session()
    with session.begin():
        res = session.query(models.UserRoleAssociation).\
                    filter_by(user_id=user_id).\
                    filter_by(role=role).\
                    all()
        for role in res:
            session.delete(role)


def user_add_role(context, user_id, role):
    session = get_session()
    with session.begin():
        user_ref = user_get(context, user_id, session=session)
        models.UserRoleAssociation(user=user_ref, role=role).\
               save(session=session)


def user_add_project_role(context, user_id, project_id, role):
    session = get_session()
    with session.begin():
        user_ref = user_get(context, user_id, session=session)
        project_ref = project_get(context, project_id, session=session)
        models.UserProjectRoleAssociation(user_id=user_ref['id'],
                                          project_id=project_ref['id'],
                                          role=role).save(session=session)


def user_update(context, user_id, values):
    session = get_session()
    with session.begin():
        user_ref = user_get(context, user_id, session=session)
        user_ref.update(values)
        user_ref.save(session=session)


###################


def project_create(_context, values):
    project_ref = models.Project()
    project_ref.update(values)
    project_ref.save()
    return project_ref


def project_add_member(context, project_id, user_id):
    session = get_session()
    with session.begin():
        project_ref = project_get(context, project_id, session=session)
        user_ref = user_get(context, user_id, session=session)

        project_ref.members += [user_ref]
        project_ref.save(session=session)


def project_get(context, id, session=None):
    if not session:
        session = get_session()

    result = session.query(models.Project).\
                     filter_by(deleted=False).\
                     filter_by(id=id).\
                     options(joinedload_all('members')).\
                     first()

    if not result:
        raise exception.ProjectNotFound(project_id=id)

    return result


def project_get_all(context):
    session = get_session()
    return session.query(models.Project).\
                   filter_by(deleted=can_read_deleted(context)).\
                   options(joinedload_all('members')).\
                   all()


def project_get_by_user(context, user_id):
    session = get_session()
    user = session.query(models.User).\
                   filter_by(deleted=can_read_deleted(context)).\
                   filter_by(id=user_id).\
                   options(joinedload_all('projects')).\
                   first()
    if not user:
        raise exception.UserNotFound(user_id=user_id)
    return user.projects


def project_remove_member(context, project_id, user_id):
    session = get_session()
    project = project_get(context, project_id, session=session)
    user = user_get(context, user_id, session=session)

    if user in project.members:
        project.members.remove(user)
        project.save(session=session)


def project_update(context, project_id, values):
    session = get_session()
    with session.begin():
        project_ref = project_get(context, project_id, session=session)
        project_ref.update(values)
        project_ref.save(session=session)


def project_delete(context, id):
    session = get_session()
    with session.begin():
        session.query(models.UserProjectAssociation).\
                filter_by(project_id=id).\
                delete()
        session.query(models.UserProjectRoleAssociation).\
                filter_by(project_id=id).\
                delete()
        project_ref = project_get(context, id, session=session)
        session.delete(project_ref)


@require_context
def project_get_networks(context, project_id, associate=True):
    # NOTE(tr3buchet): as before this function will associate
    # a project with a network if it doesn't have one and
    # associate is true
    session = get_session()
    result = session.query(models.Network).\
                     filter_by(project_id=project_id).\
                     filter_by(deleted=False).all()

    if not result:
        if not associate:
            return []
        return [network_associate(context, project_id)]
    return result


@require_context
def project_get_networks_v6(context, project_id):
    return project_get_networks(context, project_id)


###################


@require_admin_context
def migration_create(context, values):
    migration = models.Migration()
    migration.update(values)
    migration.save()
    return migration


@require_admin_context
def migration_update(context, id, values):
    session = get_session()
    with session.begin():
        migration = migration_get(context, id, session=session)
        migration.update(values)
        migration.save(session=session)
        return migration


@require_admin_context
def migration_get(context, id, session=None):
    if not session:
        session = get_session()
    result = session.query(models.Migration).\
                     filter_by(id=id).first()
    if not result:
        raise exception.MigrationNotFound(migration_id=id)
    return result


@require_admin_context
def migration_get_by_instance_and_status(context, instance_uuid, status):
    session = get_session()
    result = session.query(models.Migration).\
                     filter_by(instance_uuid=instance_uuid).\
                     filter_by(status=status).first()
    if not result:
        raise exception.MigrationNotFoundByStatus(instance_id=instance_uuid,
                                                  status=status)
    return result


##################


def console_pool_create(context, values):
    pool = models.ConsolePool()
    pool.update(values)
    pool.save()
    return pool


def console_pool_get(context, pool_id):
    session = get_session()
    result = session.query(models.ConsolePool).\
                     filter_by(deleted=False).\
                     filter_by(id=pool_id).\
                     first()
    if not result:
        raise exception.ConsolePoolNotFound(pool_id=pool_id)

    return result


def console_pool_get_by_host_type(context, compute_host, host,
                                  console_type):
    session = get_session()
    result = session.query(models.ConsolePool).\
                   filter_by(host=host).\
                   filter_by(console_type=console_type).\
                   filter_by(compute_host=compute_host).\
                   filter_by(deleted=False).\
                   options(joinedload('consoles')).\
                   first()
    if not result:
        raise exception.ConsolePoolNotFoundForHostType(host=host,
                                                  console_type=console_type,
                                                  compute_host=compute_host)
    return result


def console_pool_get_all_by_host_type(context, host, console_type):
    session = get_session()
    return session.query(models.ConsolePool).\
                   filter_by(host=host).\
                   filter_by(console_type=console_type).\
                   filter_by(deleted=False).\
                   options(joinedload('consoles')).\
                   all()


def console_create(context, values):
    console = models.Console()
    console.update(values)
    console.save()
    return console


def console_delete(context, console_id):
    session = get_session()
    with session.begin():
        # consoles are meant to be transient. (mdragon)
        session.query(models.Console).\
                filter_by(id=console_id).\
                delete()


def console_get_by_pool_instance(context, pool_id, instance_id):
    session = get_session()
    result = session.query(models.Console).\
                   filter_by(pool_id=pool_id).\
                   filter_by(instance_id=instance_id).\
                   options(joinedload('pool')).\
                   first()
    if not result:
        raise exception.ConsoleNotFoundInPoolForInstance(pool_id=pool_id,
                                                 instance_id=instance_id)
    return result


def console_get_all_by_instance(context, instance_id):
    session = get_session()
    results = session.query(models.Console).\
                   filter_by(instance_id=instance_id).\
                   options(joinedload('pool')).\
                   all()
    return results


def console_get(context, console_id, instance_id=None):
    session = get_session()
    query = session.query(models.Console).\
                    filter_by(id=console_id)
    if instance_id:
        query = query.filter_by(instance_id=instance_id)
    result = query.options(joinedload('pool')).first()
    if not result:
        if instance_id:
            raise exception.ConsoleNotFoundForInstance(console_id=console_id,
                                                       instance_id=instance_id)
        else:
            raise exception.ConsoleNotFound(console_id=console_id)
    return result


    ##################


@require_admin_context
def instance_type_create(_context, values):
    """Create a new instance type. In order to pass in extra specs,
    the values dict should contain a 'extra_specs' key/value pair:

    {'extra_specs' : {'k1': 'v1', 'k2': 'v2', ...}}

    """
    try:
        specs = values.get('extra_specs')
        specs_refs = []
        if specs:
            for k, v in specs.iteritems():
                specs_ref = models.InstanceTypeExtraSpecs()
                specs_ref['key'] = k
                specs_ref['value'] = v
                specs_refs.append(specs_ref)
        values['extra_specs'] = specs_refs
        instance_type_ref = models.InstanceTypes()
        instance_type_ref.update(values)
        instance_type_ref.save()
    except Exception, e:
        raise exception.DBError(e)
    return instance_type_ref


def _dict_with_extra_specs(inst_type_query):
    """Takes an instance OR volume type query returned by sqlalchemy
    and returns it as a dictionary, converting the extra_specs
    entry from a list of dicts:

    'extra_specs' : [{'key': 'k1', 'value': 'v1', ...}, ...]

    to a single dict:

    'extra_specs' : {'k1': 'v1'}

    """
    inst_type_dict = dict(inst_type_query)
    extra_specs = dict([(x['key'], x['value']) for x in \
                        inst_type_query['extra_specs']])
    inst_type_dict['extra_specs'] = extra_specs
    return inst_type_dict


@require_context
def instance_type_get_all(context, inactive=False):
    """
    Returns a dict describing all instance_types with name as key.
    """
    session = get_session()
    if inactive:
        inst_types = session.query(models.InstanceTypes).\
                        options(joinedload('extra_specs')).\
                        order_by("name").\
                        all()
    else:
        inst_types = session.query(models.InstanceTypes).\
                        options(joinedload('extra_specs')).\
                        filter_by(deleted=False).\
                        order_by("name").\
                        all()
    inst_dict = {}
    if inst_types:
        for i in inst_types:
            inst_dict[i['name']] = _dict_with_extra_specs(i)
    return inst_dict


@require_context
def instance_type_get(context, id):
    """Returns a dict describing specific instance_type"""
    session = get_session()
    inst_type = session.query(models.InstanceTypes).\
                    options(joinedload('extra_specs')).\
                    filter_by(id=id).\
                    first()

    if not inst_type:
        raise exception.InstanceTypeNotFound(instance_type=id)
    else:
        return _dict_with_extra_specs(inst_type)


@require_context
def instance_type_get_by_name(context, name):
    """Returns a dict describing specific instance_type"""
    session = get_session()
    inst_type = session.query(models.InstanceTypes).\
                    options(joinedload('extra_specs')).\
                    filter_by(name=name).\
                    first()
    if not inst_type:
        raise exception.InstanceTypeNotFoundByName(instance_type_name=name)
    else:
        return _dict_with_extra_specs(inst_type)


@require_context
def instance_type_get_by_flavor_id(context, id):
    """Returns a dict describing specific flavor_id"""
    try:
        flavor_id = int(id)
    except ValueError:
        raise exception.FlavorNotFound(flavor_id=id)

    session = get_session()
    inst_type = session.query(models.InstanceTypes).\
                                    options(joinedload('extra_specs')).\
                                    filter_by(flavorid=flavor_id).\
                                    first()
    if not inst_type:
        raise exception.FlavorNotFound(flavor_id=flavor_id)
    else:
        return _dict_with_extra_specs(inst_type)


@require_admin_context
def instance_type_destroy(context, name):
    """ Marks specific instance_type as deleted"""
    session = get_session()
    instance_type_ref = session.query(models.InstanceTypes).\
                                      filter_by(name=name)
    records = instance_type_ref.update(dict(deleted=True))
    if records == 0:
        raise exception.InstanceTypeNotFoundByName(instance_type_name=name)
    else:
        return instance_type_ref


@require_admin_context
def instance_type_purge(context, name):
    """ Removes specific instance_type from DB
        Usually instance_type_destroy should be used
    """
    session = get_session()
    instance_type_ref = session.query(models.InstanceTypes).\
                                      filter_by(name=name)
    records = instance_type_ref.delete()
    if records == 0:
        raise exception.InstanceTypeNotFoundByName(instance_type_name=name)
    else:
        return instance_type_ref


####################


@require_admin_context
def zone_create(context, values):
    zone = models.Zone()
    zone.update(values)
    zone.save()
    return zone


@require_admin_context
def zone_update(context, zone_id, values):
    session = get_session()
    zone = session.query(models.Zone).filter_by(id=zone_id).first()
    if not zone:
        raise exception.ZoneNotFound(zone_id=zone_id)
    zone.update(values)
    zone.save(session=session)
    return zone


@require_admin_context
def zone_delete(context, zone_id):
    session = get_session()
    with session.begin():
        session.query(models.Zone).\
                filter_by(id=zone_id).\
                delete()


@require_admin_context
def zone_get(context, zone_id):
    session = get_session()
    result = session.query(models.Zone).filter_by(id=zone_id).first()
    if not result:
        raise exception.ZoneNotFound(zone_id=zone_id)
    return result


@require_admin_context
def zone_get_all(context):
    session = get_session()
    return session.query(models.Zone).all()


####################


@require_context
@require_instance_exists
def instance_metadata_get(context, instance_id):
    session = get_session()

    meta_results = session.query(models.InstanceMetadata).\
                    filter_by(instance_id=instance_id).\
                    filter_by(deleted=False).\
                    all()

    meta_dict = {}
    for i in meta_results:
        meta_dict[i['key']] = i['value']
    return meta_dict


@require_context
@require_instance_exists
def instance_metadata_delete(context, instance_id, key):
    session = get_session()
    session.query(models.InstanceMetadata).\
        filter_by(instance_id=instance_id).\
        filter_by(key=key).\
        filter_by(deleted=False).\
        update({'deleted': True,
                'deleted_at': utils.utcnow(),
                'updated_at': literal_column('updated_at')})


@require_context
@require_instance_exists
def instance_metadata_delete_all(context, instance_id):
    session = get_session()
    session.query(models.InstanceMetadata).\
        filter_by(instance_id=instance_id).\
        filter_by(deleted=False).\
        update({'deleted': True,
                'deleted_at': utils.utcnow(),
                'updated_at': literal_column('updated_at')})


@require_context
@require_instance_exists
def instance_metadata_get_item(context, instance_id, key, session=None):
    if not session:
        session = get_session()

    meta_result = session.query(models.InstanceMetadata).\
                    filter_by(instance_id=instance_id).\
                    filter_by(key=key).\
                    filter_by(deleted=False).\
                    first()

    if not meta_result:
        raise exception.InstanceMetadataNotFound(metadata_key=key,
                                                 instance_id=instance_id)
    return meta_result


@require_context
@require_instance_exists
def instance_metadata_update(context, instance_id, metadata, delete):
    session = get_session()

    # Set existing metadata to deleted if delete argument is True
    if delete:
        original_metadata = instance_metadata_get(context, instance_id)
        for meta_key, meta_value in original_metadata.iteritems():
            if meta_key not in metadata:
                meta_ref = instance_metadata_get_item(context, instance_id,
                                                      meta_key, session)
                meta_ref.update({'deleted': True})
                meta_ref.save(session=session)

    meta_ref = None

    # Now update all existing items with new values, or create new meta objects
    for meta_key, meta_value in metadata.iteritems():

        # update the value whether it exists or not
        item = {"value": meta_value}

        try:
            meta_ref = instance_metadata_get_item(context, instance_id,
                                                  meta_key, session)
        except exception.InstanceMetadataNotFound, e:
            meta_ref = models.InstanceMetadata()
            item.update({"key": meta_key, "instance_id": instance_id})

        meta_ref.update(item)
        meta_ref.save(session=session)

    return metadata


####################


@require_admin_context
def agent_build_create(context, values):
    agent_build_ref = models.AgentBuild()
    agent_build_ref.update(values)
    agent_build_ref.save()
    return agent_build_ref


@require_admin_context
def agent_build_get_by_triple(context, hypervisor, os, architecture,
                              session=None):
    if not session:
        session = get_session()
    return session.query(models.AgentBuild).\
                   filter_by(hypervisor=hypervisor).\
                   filter_by(os=os).\
                   filter_by(architecture=architecture).\
                   filter_by(deleted=False).\
                   first()


@require_admin_context
def agent_build_get_all(context):
    session = get_session()
    return session.query(models.AgentBuild).\
                   filter_by(deleted=False).\
                   all()


@require_admin_context
def agent_build_destroy(context, agent_build_id):
    session = get_session()
    with session.begin():
        session.query(models.AgentBuild).\
                filter_by(id=agent_build_id).\
                update({'deleted': True,
                        'deleted_at': utils.utcnow(),
                        'updated_at': literal_column('updated_at')})


@require_admin_context
def agent_build_update(context, agent_build_id, values):
    session = get_session()
    with session.begin():
        agent_build_ref = session.query(models.AgentBuild).\
                   filter_by(id=agent_build_id). \
                   first()
        agent_build_ref.update(values)
        agent_build_ref.save(session=session)


####################


@require_context
def instance_type_extra_specs_get(context, instance_type_id):
    session = get_session()

    spec_results = session.query(models.InstanceTypeExtraSpecs).\
                    filter_by(instance_type_id=instance_type_id).\
                    filter_by(deleted=False).\
                    all()

    spec_dict = {}
    for i in spec_results:
        spec_dict[i['key']] = i['value']
    return spec_dict


@require_context
def instance_type_extra_specs_delete(context, instance_type_id, key):
    session = get_session()
    session.query(models.InstanceTypeExtraSpecs).\
        filter_by(instance_type_id=instance_type_id).\
        filter_by(key=key).\
        filter_by(deleted=False).\
        update({'deleted': True,
                'deleted_at': utils.utcnow(),
                'updated_at': literal_column('updated_at')})


@require_context
def instance_type_extra_specs_get_item(context, instance_type_id, key,
                                       session=None):

    if not session:
        session = get_session()

    spec_result = session.query(models.InstanceTypeExtraSpecs).\
                    filter_by(instance_type_id=instance_type_id).\
                    filter_by(key=key).\
                    filter_by(deleted=False).\
                    first()

    if not spec_result:
        raise exception.\
           InstanceTypeExtraSpecsNotFound(extra_specs_key=key,
                                        instance_type_id=instance_type_id)
    return spec_result


@require_context
def instance_type_extra_specs_update_or_create(context, instance_type_id,
                                               specs):
    session = get_session()
    spec_ref = None
    for key, value in specs.iteritems():
        try:
            spec_ref = instance_type_extra_specs_get_item(
                context, instance_type_id, key, session)
        except exception.InstanceTypeExtraSpecsNotFound, e:
            spec_ref = models.InstanceTypeExtraSpecs()
        spec_ref.update({"key": key, "value": value,
                         "instance_type_id": instance_type_id,
                         "deleted": 0})
        spec_ref.save(session=session)
    return specs


##################


@require_admin_context
def volume_type_create(_context, values):
    """Create a new instance type. In order to pass in extra specs,
    the values dict should contain a 'extra_specs' key/value pair:

    {'extra_specs' : {'k1': 'v1', 'k2': 'v2', ...}}

    """
    try:
        specs = values.get('extra_specs')

        values['extra_specs'] = _metadata_refs(values.get('extra_specs'),
                                                models.VolumeTypeExtraSpecs)
        volume_type_ref = models.VolumeTypes()
        volume_type_ref.update(values)
        volume_type_ref.save()
    except Exception, e:
        raise exception.DBError(e)
    return volume_type_ref


@require_context
def volume_type_get_all(context, inactive=False, filters={}):
    """
    Returns a dict describing all volume_types with name as key.
    """
    session = get_session()
    if inactive:
        vol_types = session.query(models.VolumeTypes).\
                        options(joinedload('extra_specs')).\
                        order_by("name").\
                        all()
    else:
        vol_types = session.query(models.VolumeTypes).\
                        options(joinedload('extra_specs')).\
                        filter_by(deleted=False).\
                        order_by("name").\
                        all()
    vol_dict = {}
    if vol_types:
        for i in vol_types:
            vol_dict[i['name']] = _dict_with_extra_specs(i)
    return vol_dict


@require_context
def volume_type_get(context, id):
    """Returns a dict describing specific volume_type"""
    session = get_session()
    vol_type = session.query(models.VolumeTypes).\
                    options(joinedload('extra_specs')).\
                    filter_by(id=id).\
                    first()

    if not vol_type:
        raise exception.VolumeTypeNotFound(volume_type=id)
    else:
        return _dict_with_extra_specs(vol_type)


@require_context
def volume_type_get_by_name(context, name):
    """Returns a dict describing specific volume_type"""
    session = get_session()
    vol_type = session.query(models.VolumeTypes).\
                    options(joinedload('extra_specs')).\
                    filter_by(name=name).\
                    first()
    if not vol_type:
        raise exception.VolumeTypeNotFoundByName(volume_type_name=name)
    else:
        return _dict_with_extra_specs(vol_type)


@require_admin_context
def volume_type_destroy(context, name):
    """ Marks specific volume_type as deleted"""
    session = get_session()
    volume_type_ref = session.query(models.VolumeTypes).\
                                      filter_by(name=name)
    records = volume_type_ref.update(dict(deleted=True))
    if records == 0:
        raise exception.VolumeTypeNotFoundByName(volume_type_name=name)
    else:
        return volume_type_ref


@require_admin_context
def volume_type_purge(context, name):
    """ Removes specific volume_type from DB
        Usually volume_type_destroy should be used
    """
    session = get_session()
    volume_type_ref = session.query(models.VolumeTypes).\
                                      filter_by(name=name)
    records = volume_type_ref.delete()
    if records == 0:
        raise exception.VolumeTypeNotFoundByName(volume_type_name=name)
    else:
        return volume_type_ref


####################


@require_context
def volume_type_extra_specs_get(context, volume_type_id):
    session = get_session()

    spec_results = session.query(models.VolumeTypeExtraSpecs).\
                    filter_by(volume_type_id=volume_type_id).\
                    filter_by(deleted=False).\
                    all()

    spec_dict = {}
    for i in spec_results:
        spec_dict[i['key']] = i['value']
    return spec_dict


@require_context
def volume_type_extra_specs_delete(context, volume_type_id, key):
    session = get_session()
    session.query(models.VolumeTypeExtraSpecs).\
        filter_by(volume_type_id=volume_type_id).\
        filter_by(key=key).\
        filter_by(deleted=False).\
        update({'deleted': True,
                'deleted_at': utils.utcnow(),
                'updated_at': literal_column('updated_at')})


@require_context
def volume_type_extra_specs_get_item(context, volume_type_id, key,
                                       session=None):

    if not session:
        session = get_session()

    spec_result = session.query(models.VolumeTypeExtraSpecs).\
                    filter_by(volume_type_id=volume_type_id).\
                    filter_by(key=key).\
                    filter_by(deleted=False).\
                    first()

    if not spec_result:
        raise exception.\
           VolumeTypeExtraSpecsNotFound(extra_specs_key=key,
                                        volume_type_id=volume_type_id)
    return spec_result


@require_context
def volume_type_extra_specs_update_or_create(context, volume_type_id,
                                             specs):
    session = get_session()
    spec_ref = None
    for key, value in specs.iteritems():
        try:
            spec_ref = volume_type_extra_specs_get_item(
                context, volume_type_id, key, session)
        except exception.VolumeTypeExtraSpecsNotFound, e:
            spec_ref = models.VolumeTypeExtraSpecs()
        spec_ref.update({"key": key, "value": value,
                         "volume_type_id": volume_type_id,
                         "deleted": 0})
        spec_ref.save(session=session)
    return specs


    ####################


@require_admin_context
def vsa_create(context, values):
    """
    Creates Virtual Storage Array record.
    """
    try:
        vsa_ref = models.VirtualStorageArray()
        vsa_ref.update(values)
        vsa_ref.save()
    except Exception, e:
        raise exception.DBError(e)
    return vsa_ref


@require_admin_context
def vsa_update(context, vsa_id, values):
    """
    Updates Virtual Storage Array record.
    """
    session = get_session()
    with session.begin():
        vsa_ref = vsa_get(context, vsa_id, session=session)
        vsa_ref.update(values)
        vsa_ref.save(session=session)
    return vsa_ref


@require_admin_context
def vsa_destroy(context, vsa_id):
    """
    Deletes Virtual Storage Array record.
    """
    session = get_session()
    with session.begin():
        session.query(models.VirtualStorageArray).\
                filter_by(id=vsa_id).\
                update({'deleted': True,
                        'deleted_at': utils.utcnow(),
                        'updated_at': literal_column('updated_at')})


@require_context
def vsa_get(context, vsa_id, session=None):
    """
    Get Virtual Storage Array record by ID.
    """
    if not session:
        session = get_session()
    result = None

    if is_admin_context(context):
        result = session.query(models.VirtualStorageArray).\
                         options(joinedload('vsa_instance_type')).\
                         filter_by(id=vsa_id).\
                         filter_by(deleted=can_read_deleted(context)).\
                         first()
    elif is_user_context(context):
        result = session.query(models.VirtualStorageArray).\
                         options(joinedload('vsa_instance_type')).\
                         filter_by(project_id=context.project_id).\
                         filter_by(id=vsa_id).\
                         filter_by(deleted=False).\
                         first()
    if not result:
        raise exception.VirtualStorageArrayNotFound(id=vsa_id)

    return result


@require_admin_context
def vsa_get_all(context):
    """
    Get all Virtual Storage Array records.
    """
    session = get_session()
    return session.query(models.VirtualStorageArray).\
                   options(joinedload('vsa_instance_type')).\
                   filter_by(deleted=can_read_deleted(context)).\
                   all()


@require_context
def vsa_get_all_by_project(context, project_id):
    """
    Get all Virtual Storage Array records by project ID.
    """
    authorize_project_context(context, project_id)

    session = get_session()
    return session.query(models.VirtualStorageArray).\
                   options(joinedload('vsa_instance_type')).\
                   filter_by(project_id=project_id).\
                   filter_by(deleted=can_read_deleted(context)).\
                   all()


    ####################