/usr/share/pyshared/nova/compute/manager.py is in python-nova 2012.1-0ubuntu2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# 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.
"""Handles all processes relating to instances (guest vms).
The :py:class:`ComputeManager` class is a :py:class:`nova.manager.Manager` that
handles RPC calls relating to creating instances. It is responsible for
building a disk image, launching it via the underlying virtualization driver,
responding to calls to check its state, attaching persistent storage, and
terminating it.
**Related Flags**
:instances_path: Where instances are kept on disk
:compute_driver: Name of class that is used to handle virtualization, loaded
by :func:`nova.utils.import_object`
"""
import contextlib
import functools
import os
import socket
import sys
import tempfile
import time
import traceback
from eventlet import greenthread
from nova import block_device
import nova.context
from nova.compute import aggregate_states
from nova.compute import instance_types
from nova.compute import power_state
from nova.compute import task_states
from nova.compute import utils as compute_utils
from nova.compute import vm_states
from nova import exception
from nova import flags
import nova.image
from nova import log as logging
from nova import manager
from nova import network
from nova.network import model as network_model
from nova.notifier import api as notifier
from nova.openstack.common import cfg
from nova import rpc
from nova import utils
from nova.virt import driver
from nova import vnc
from nova import volume
compute_opts = [
cfg.StrOpt('instances_path',
default='$state_path/instances',
help='where instances are stored on disk'),
cfg.StrOpt('compute_driver',
default='nova.virt.connection.get_connection',
help='Driver to use for controlling virtualization'),
cfg.StrOpt('console_host',
default=socket.gethostname(),
help='Console proxy host to use to connect '
'to instances on this host.'),
cfg.IntOpt('live_migration_retry_count',
default=30,
help="Number of 1 second retries needed in live_migration"),
cfg.IntOpt("reboot_timeout",
default=0,
help="Automatically hard reboot an instance if it has been "
"stuck in a rebooting state longer than N seconds. "
"Set to 0 to disable."),
cfg.IntOpt("rescue_timeout",
default=0,
help="Automatically unrescue an instance after N seconds. "
"Set to 0 to disable."),
cfg.IntOpt("resize_confirm_window",
default=0,
help="Automatically confirm resizes after N seconds. "
"Set to 0 to disable."),
cfg.IntOpt('host_state_interval',
default=120,
help='Interval in seconds for querying the host status'),
cfg.IntOpt("running_deleted_instance_timeout",
default=0,
help="Number of seconds after being deleted when a running "
"instance should be considered eligible for cleanup."),
cfg.IntOpt("running_deleted_instance_poll_interval",
default=30,
help="Number of periodic scheduler ticks to wait between "
"runs of the cleanup task."),
cfg.StrOpt("running_deleted_instance_action",
default="log",
help="Action to take if a running deleted instance is detected."
"Valid options are 'noop', 'log' and 'reap'. "
"Set to 'noop' to disable."),
cfg.IntOpt("image_cache_manager_interval",
default=40,
help="Number of periodic scheduler ticks to wait between "
"runs of the image cache manager."),
cfg.IntOpt("heal_instance_info_cache_interval",
default=60,
help="Number of seconds between instance info_cache self "
"healing updates")
]
FLAGS = flags.FLAGS
FLAGS.register_opts(compute_opts)
LOG = logging.getLogger(__name__)
def publisher_id(host=None):
return notifier.publisher_id("compute", host)
def checks_instance_lock(function):
"""Decorator to prevent action against locked instances for non-admins."""
@functools.wraps(function)
def decorated_function(self, context, instance_uuid, *args, **kwargs):
LOG.info(_("check_instance_lock: decorating: |%s|"), function,
context=context)
LOG.info(_("check_instance_lock: arguments: |%(self)s| |%(context)s|"
" |%(instance_uuid)s|") % locals(), context=context)
locked = self.get_lock(context, instance_uuid)
admin = context.is_admin
LOG.info(_("check_instance_lock: locked: |%s|"), locked,
context=context)
LOG.info(_("check_instance_lock: admin: |%s|"), admin,
context=context)
# if admin or unlocked call function otherwise log error
if admin or not locked:
LOG.info(_("check_instance_lock: executing: |%s|"), function,
context=context)
function(self, context, instance_uuid, *args, **kwargs)
else:
LOG.error(_("check_instance_lock: not executing |%s|"),
function, context=context)
return False
return decorated_function
def wrap_instance_fault(function):
"""Wraps a method to catch exceptions related to instances.
This decorator wraps a method to catch any exceptions having to do with
an instance that may get thrown. It then logs an instance fault in the db.
"""
@functools.wraps(function)
def decorated_function(self, context, instance_uuid, *args, **kwargs):
try:
return function(self, context, instance_uuid, *args, **kwargs)
except exception.InstanceNotFound:
raise
except Exception, e:
with utils.save_and_reraise_exception():
self.add_instance_fault_from_exc(context, instance_uuid, e,
sys.exc_info())
return decorated_function
def _get_image_meta(context, image_ref):
image_service, image_id = nova.image.get_image_service(context, image_ref)
return image_service.show(context, image_id)
class ComputeManager(manager.SchedulerDependentManager):
"""Manages the running instances from creation to destruction."""
def __init__(self, compute_driver=None, *args, **kwargs):
"""Load configuration options and connect to the hypervisor."""
# TODO(vish): sync driver creation logic with the rest of the system
# and re-document the module docstring
if not compute_driver:
compute_driver = FLAGS.compute_driver
try:
self.driver = utils.check_isinstance(
utils.import_object(compute_driver),
driver.ComputeDriver)
except ImportError as e:
LOG.error(_("Unable to load the virtualization driver: %s") % (e))
sys.exit(1)
self.network_api = network.API()
self.volume_api = volume.API()
self.network_manager = utils.import_object(FLAGS.network_manager)
self._last_host_check = 0
self._last_bw_usage_poll = 0
self._last_info_cache_heal = 0
super(ComputeManager, self).__init__(service_name="compute",
*args, **kwargs)
def _instance_update(self, context, instance_id, **kwargs):
"""Update an instance in the database using kwargs as value."""
return self.db.instance_update(context, instance_id, kwargs)
def _set_instance_error_state(self, context, instance_uuid):
try:
self._instance_update(context,
instance_uuid, vm_state=vm_states.ERROR)
except exception.InstanceNotFound:
LOG.debug(_("Instance %(instance_uuid)s has been destroyed "
"from under us while trying to set it to ERROR") %
locals())
def init_host(self):
"""Initialization for a standalone compute service."""
self.driver.init_host(host=self.host)
context = nova.context.get_admin_context()
instances = self.db.instance_get_all_by_host(context, self.host)
for instance in instances:
instance_uuid = instance['uuid']
db_state = instance['power_state']
drv_state = self._get_power_state(context, instance)
expect_running = (db_state == power_state.RUNNING and
drv_state != db_state)
LOG.debug(_('Current state is %(drv_state)s, state in DB is '
'%(db_state)s.'), locals(), instance=instance)
if ((expect_running and FLAGS.resume_guests_state_on_host_boot) or
FLAGS.start_guests_on_host_boot):
LOG.info(_('Rebooting instance after nova-compute restart.'),
locals(), instance=instance)
self.reboot_instance(context, instance['uuid'])
elif drv_state == power_state.RUNNING:
# Hyper-V and VMWareAPI drivers will raise an exception
try:
net_info = self._get_instance_nw_info(context, instance)
self.driver.ensure_filtering_rules_for_instance(instance,
self._legacy_nw_info(net_info))
except NotImplementedError:
LOG.warning(_('Hypervisor driver does not support '
'firewall rules'))
def _get_power_state(self, context, instance):
"""Retrieve the power state for the given instance."""
LOG.debug(_('Checking state'), instance=instance)
try:
return self.driver.get_info(instance)["state"]
except exception.NotFound:
return power_state.FAILED
def get_console_topic(self, context, **kwargs):
"""Retrieves the console host for a project on this host.
Currently this is just set in the flags for each compute host.
"""
#TODO(mdragon): perhaps make this variable by console_type?
return self.db.queue_get_for(context,
FLAGS.console_topic,
FLAGS.console_host)
def get_console_pool_info(self, context, console_type):
return self.driver.get_console_pool_info(console_type)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
def refresh_security_group_rules(self, context, security_group_id,
**kwargs):
"""Tell the virtualization driver to refresh security group rules.
Passes straight through to the virtualization driver.
"""
return self.driver.refresh_security_group_rules(security_group_id)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
def refresh_security_group_members(self, context,
security_group_id, **kwargs):
"""Tell the virtualization driver to refresh security group members.
Passes straight through to the virtualization driver.
"""
return self.driver.refresh_security_group_members(security_group_id)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
def refresh_provider_fw_rules(self, context, **kwargs):
"""This call passes straight through to the virtualization driver."""
return self.driver.refresh_provider_fw_rules(**kwargs)
def _get_instance_nw_info(self, context, instance):
"""Get a list of dictionaries of network data of an instance.
Returns an empty list if stub_network flag is set."""
if FLAGS.stub_network:
return network_model.NetworkInfo()
# get the network info from network
network_info = self.network_api.get_instance_nw_info(context,
instance)
return network_info
def _legacy_nw_info(self, network_info):
"""Converts the model nw_info object to legacy style"""
if self.driver.legacy_nwinfo():
network_info = compute_utils.legacy_network_info(network_info)
return network_info
def _setup_block_device_mapping(self, context, instance):
"""setup volumes for block device mapping"""
block_device_mapping = []
swap = None
ephemerals = []
for bdm in self.db.block_device_mapping_get_all_by_instance(
context, instance['id']):
LOG.debug(_('Setting up bdm %s'), bdm, instance=instance)
if bdm['no_device']:
continue
if bdm['virtual_name']:
virtual_name = bdm['virtual_name']
device_name = bdm['device_name']
assert block_device.is_swap_or_ephemeral(virtual_name)
if virtual_name == 'swap':
swap = {'device_name': device_name,
'swap_size': bdm['volume_size']}
elif block_device.is_ephemeral(virtual_name):
eph = {'num': block_device.ephemeral_num(virtual_name),
'virtual_name': virtual_name,
'device_name': device_name,
'size': bdm['volume_size']}
ephemerals.append(eph)
continue
if ((bdm['snapshot_id'] is not None) and
(bdm['volume_id'] is None)):
# TODO(yamahata): default name and description
snapshot = self.volume_api.get_snapshot(context,
bdm['snapshot_id'])
vol = self.volume_api.create(context, bdm['volume_size'],
'', '', snapshot)
# TODO(yamahata): creating volume simultaneously
# reduces creation time?
self.volume_api.wait_creation(context, vol)
self.db.block_device_mapping_update(
context, bdm['id'], {'volume_id': vol['id']})
bdm['volume_id'] = vol['id']
if bdm['volume_id'] is not None:
volume = self.volume_api.get(context, bdm['volume_id'])
self.volume_api.check_attach(context, volume)
cinfo = self._attach_volume_boot(context,
instance,
volume,
bdm['device_name'])
self.db.block_device_mapping_update(
context, bdm['id'],
{'connection_info': utils.dumps(cinfo)})
block_device_mapping.append({'connection_info': cinfo,
'mount_device':
bdm['device_name']})
return {
'root_device_name': instance['root_device_name'],
'swap': swap,
'ephemerals': ephemerals,
'block_device_mapping': block_device_mapping
}
def _is_instance_terminated(self, instance_uuid):
"""Instance in DELETING task state or not found in DB"""
context = nova.context.get_admin_context()
try:
instance = self.db.instance_get_by_uuid(context, instance_uuid)
if instance['task_state'] == task_states.DELETING:
return True
return False
except Exception:
return True
def _shutdown_instance_even_if_deleted(self, context, instance_uuid):
"""Call terminate_instance even for already deleted instances"""
try:
try:
self.terminate_instance(context, instance_uuid)
except exception.InstanceNotFound:
LOG.info(_("Instance %s already deleted from database. "
"Attempting forceful vm deletion")
% instance_uuid)
ctxt = nova.context.get_admin_context(read_deleted='yes')
self.terminate_instance(ctxt, instance_uuid)
except Exception as ex:
LOG.exception(_("Exception encountered while terminating the "
"instance %s") % instance_uuid)
def _run_instance(self, context, instance_uuid,
requested_networks=None,
injected_files=[],
admin_password=None,
is_first_time=False,
**kwargs):
"""Launch a new instance with specified options."""
context = context.elevated()
try:
instance = self.db.instance_get_by_uuid(context, instance_uuid)
self._check_instance_not_already_created(context, instance)
image_meta = self._check_image_size(context, instance)
self._start_building(context, instance)
self._notify_about_instance_usage(instance, "create.start")
network_info = self._allocate_network(context, instance,
requested_networks)
try:
block_device_info = self._prep_block_device(context, instance)
instance = self._spawn(context, instance, image_meta,
network_info, block_device_info,
injected_files, admin_password)
except Exception:
with utils.save_and_reraise_exception():
self._deallocate_network(context, instance)
if (is_first_time and not instance['access_ip_v4']
and not instance['access_ip_v6']):
self._update_access_ip(context, instance, network_info)
self._notify_about_instance_usage(instance, "create.end",
network_info=network_info)
if self._is_instance_terminated(instance_uuid):
raise exception.InstanceNotFound
except exception.InstanceNotFound:
LOG.exception(_("Instance %s not found.") % instance_uuid)
# assuming the instance was already deleted, run "delete" again
# just in case
self._shutdown_instance_even_if_deleted(context, instance_uuid)
return
except Exception as e:
with utils.save_and_reraise_exception():
self._set_instance_error_state(context, instance_uuid)
def _update_access_ip(self, context, instance, nw_info):
"""Update the access ip values for a given instance.
If FLAGS.default_access_ip_network_name is set, this method will
grab the corresponding network and set the access ip values
accordingly. Note that when there are multiple ips to choose from,
an arbitrary one will be chosen.
"""
network_name = FLAGS.default_access_ip_network_name
if not network_name:
return
update_info = {}
for vif in nw_info:
if vif['network']['label'] == network_name:
for ip in vif.fixed_ips():
if ip['version'] == 4:
update_info['access_ip_v4'] = ip['address']
if ip['version'] == 6:
update_info['access_ip_v6'] = ip['address']
if update_info:
self.db.instance_update(context, instance.uuid, update_info)
def _check_instance_not_already_created(self, context, instance):
"""Ensure an instance with the same name is not already present."""
if self.driver.instance_exists(instance['name']):
_msg = _("Instance has already been created")
raise exception.Invalid(_msg)
def _check_image_size(self, context, instance):
"""Ensure image is smaller than the maximum size allowed by the
instance_type.
The image stored in Glance is potentially compressed, so we use two
checks to ensure that the size isn't exceeded:
1) This one - checks compressed size, this a quick check to
eliminate any images which are obviously too large
2) Check uncompressed size in nova.virt.xenapi.vm_utils. This
is a slower check since it requires uncompressing the entire
image, but is accurate because it reflects the image's
actual size.
"""
image_meta = _get_image_meta(context, instance['image_ref'])
try:
size_bytes = image_meta['size']
except KeyError:
# Size is not a required field in the image service (yet), so
# we are unable to rely on it being there even though it's in
# glance.
# TODO(jk0): Should size be required in the image service?
return image_meta
instance_type_id = instance['instance_type_id']
instance_type = instance_types.get_instance_type(instance_type_id)
allowed_size_gb = instance_type['root_gb']
# NOTE(johannes): root_gb is allowed to be 0 for legacy reasons
# since libvirt interpreted the value differently than other
# drivers. A value of 0 means don't check size.
if not allowed_size_gb:
return image_meta
allowed_size_bytes = allowed_size_gb * 1024 * 1024 * 1024
image_id = image_meta['id']
LOG.debug(_("image_id=%(image_id)s, image_size_bytes="
"%(size_bytes)d, allowed_size_bytes="
"%(allowed_size_bytes)d") % locals())
if size_bytes > allowed_size_bytes:
LOG.info(_("Image '%(image_id)s' size %(size_bytes)d exceeded"
" instance_type allowed size "
"%(allowed_size_bytes)d")
% locals())
raise exception.ImageTooLarge()
return image_meta
def _start_building(self, context, instance):
"""Save the host and launched_on fields and log appropriately."""
LOG.audit(_('Starting instance...'), context=context,
instance=instance)
self._instance_update(context, instance['uuid'],
host=self.host, launched_on=self.host,
vm_state=vm_states.BUILDING,
task_state=None)
def _allocate_network(self, context, instance, requested_networks):
"""Allocate networks for an instance and return the network info"""
if FLAGS.stub_network:
LOG.debug(_('Skipping network allocation for instance'),
instance=instance)
return network_model.NetworkInfo()
self._instance_update(context, instance['uuid'],
vm_state=vm_states.BUILDING,
task_state=task_states.NETWORKING)
is_vpn = instance['image_ref'] == str(FLAGS.vpn_image_id)
try:
# allocate and get network info
network_info = self.network_api.allocate_for_instance(
context, instance, vpn=is_vpn,
requested_networks=requested_networks)
except Exception:
LOG.exception(_('Instance failed network setup'),
instance=instance)
raise
LOG.debug(_('Instance network_info: |%s|'), network_info,
instance=instance)
return network_info
def _prep_block_device(self, context, instance):
"""Set up the block device for an instance with error logging"""
self._instance_update(context, instance['uuid'],
vm_state=vm_states.BUILDING,
task_state=task_states.BLOCK_DEVICE_MAPPING)
try:
return self._setup_block_device_mapping(context, instance)
except Exception:
LOG.exception(_('Instance failed block device setup'),
instance=instance)
raise
def _spawn(self, context, instance, image_meta, network_info,
block_device_info, injected_files, admin_pass):
"""Spawn an instance with error logging and update its power state"""
self._instance_update(context, instance['uuid'],
vm_state=vm_states.BUILDING,
task_state=task_states.SPAWNING)
instance['injected_files'] = injected_files
instance['admin_pass'] = admin_pass
try:
self.driver.spawn(context, instance, image_meta,
self._legacy_nw_info(network_info), block_device_info)
except Exception:
LOG.exception(_('Instance failed to spawn'), instance=instance)
raise
current_power_state = self._get_power_state(context, instance)
return self._instance_update(context, instance['uuid'],
power_state=current_power_state,
vm_state=vm_states.ACTIVE,
task_state=None,
launched_at=utils.utcnow())
def _notify_about_instance_usage(self, instance, event_suffix,
usage_info=None, network_info=None):
if not usage_info:
usage_info = utils.usage_from_instance(instance,
network_info=network_info)
notifier.notify('compute.%s' % self.host,
'compute.instance.%s' % event_suffix,
notifier.INFO, usage_info)
def _deallocate_network(self, context, instance):
if not FLAGS.stub_network:
LOG.debug(_('Deallocating network for instance'),
instance=instance)
self.network_api.deallocate_for_instance(context, instance)
def _get_instance_volume_bdms(self, context, instance_id):
bdms = self.db.block_device_mapping_get_all_by_instance(context,
instance_id)
return [bdm for bdm in bdms if bdm['volume_id']]
def _get_instance_volume_bdm(self, context, instance_id, volume_id):
bdms = self._get_instance_volume_bdms(context, instance_id)
for bdm in bdms:
# NOTE(vish): Comparing as strings because the os_api doesn't
# convert to integer and we may wish to support uuids
# in the future.
if str(bdm['volume_id']) == str(volume_id):
return bdm
def _get_instance_volume_block_device_info(self, context, instance_id):
bdms = self._get_instance_volume_bdms(context, instance_id)
block_device_mapping = []
for bdm in bdms:
cinfo = utils.loads(bdm['connection_info'])
block_device_mapping.append({'connection_info': cinfo,
'mount_device':
bdm['device_name']})
# NOTE(vish): The mapping is passed in so the driver can disconnect
# from remote volumes if necessary
return {'block_device_mapping': block_device_mapping}
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@wrap_instance_fault
def run_instance(self, context, instance_uuid, **kwargs):
@utils.synchronized(instance_uuid)
def do_run_instance():
self._run_instance(context, instance_uuid, **kwargs)
do_run_instance()
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def start_instance(self, context, instance_uuid):
@utils.synchronized(instance_uuid)
def do_start_instance():
"""Starting an instance on this host."""
# TODO(yamahata): injected_files isn't supported.
# Anyway OSAPI doesn't support stop/start yet
# FIXME(vish): I've kept the files during stop instance, but
# I think start will fail due to the files still
self._run_instance(context, instance_uuid)
do_start_instance()
def _shutdown_instance(self, context, instance, action_str):
"""Shutdown an instance on this host."""
context = context.elevated()
instance_id = instance['id']
instance_uuid = instance['uuid']
LOG.audit(_('%(action_str)s instance') % {'action_str': action_str},
context=context, instance=instance)
self._notify_about_instance_usage(instance, "shutdown.start")
# get network info before tearing down
network_info = self._get_instance_nw_info(context, instance)
# tear down allocated network structure
self._deallocate_network(context, instance)
# NOTE(vish) get bdms before destroying the instance
bdms = self._get_instance_volume_bdms(context, instance_id)
block_device_info = self._get_instance_volume_block_device_info(
context, instance_id)
self.driver.destroy(instance, self._legacy_nw_info(network_info),
block_device_info)
for bdm in bdms:
try:
# NOTE(vish): actual driver detach done in driver.destroy, so
# just tell nova-volume that we are done with it.
volume = self.volume_api.get(context, bdm['volume_id'])
connector = self.driver.get_volume_connector(instance)
self.volume_api.terminate_connection(context,
volume,
connector)
self.volume_api.detach(context, volume)
except exception.DiskNotFound as exc:
LOG.warn(_('Ignoring DiskNotFound: %s') % exc,
instance=instance)
self._notify_about_instance_usage(instance, "shutdown.end")
def _cleanup_volumes(self, context, instance_id):
bdms = self.db.block_device_mapping_get_all_by_instance(context,
instance_id)
for bdm in bdms:
LOG.debug(_("terminating bdm %s") % bdm)
if bdm['volume_id'] and bdm['delete_on_termination']:
volume = self.volume_api.get(context, bdm['volume_id'])
self.volume_api.delete(context, volume)
# NOTE(vish): bdms will be deleted on instance destroy
def _delete_instance(self, context, instance):
"""Delete an instance on this host."""
instance_id = instance['id']
self._notify_about_instance_usage(instance, "delete.start")
self._shutdown_instance(context, instance, 'Terminating')
self._cleanup_volumes(context, instance_id)
self._instance_update(context,
instance_id,
vm_state=vm_states.DELETED,
task_state=None,
terminated_at=utils.utcnow())
self.db.instance_destroy(context, instance_id)
self._notify_about_instance_usage(instance, "delete.end")
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def terminate_instance(self, context, instance_uuid):
"""Terminate an instance on this host."""
@utils.synchronized(instance_uuid)
def do_terminate_instance():
elevated = context.elevated()
instance = self.db.instance_get_by_uuid(elevated, instance_uuid)
compute_utils.notify_usage_exists(instance, current_period=True)
try:
self._delete_instance(context, instance)
except exception.InstanceTerminationFailure as error:
msg = _('%s. Setting instance vm_state to ERROR')
LOG.error(msg % error)
self._set_instance_error_state(context, instance_uuid)
except exception.InstanceNotFound as e:
LOG.warn(e)
do_terminate_instance()
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def stop_instance(self, context, instance_uuid):
"""Stopping an instance on this host."""
@utils.synchronized(instance_uuid)
def do_stop_instance():
instance = self.db.instance_get_by_uuid(context, instance_uuid)
self._shutdown_instance(context, instance, 'Stopping')
self._instance_update(context,
instance_uuid,
vm_state=vm_states.STOPPED,
task_state=None)
do_stop_instance()
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def power_off_instance(self, context, instance_uuid):
"""Power off an instance on this host."""
instance = self.db.instance_get_by_uuid(context, instance_uuid)
self._notify_about_instance_usage(instance, "power_off.start")
self.driver.power_off(instance)
current_power_state = self._get_power_state(context, instance)
self._instance_update(context,
instance_uuid,
power_state=current_power_state,
task_state=None)
self._notify_about_instance_usage(instance, "power_off.end")
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def power_on_instance(self, context, instance_uuid):
"""Power on an instance on this host."""
instance = self.db.instance_get_by_uuid(context, instance_uuid)
self._notify_about_instance_usage(instance, "power_on.start")
self.driver.power_on(instance)
current_power_state = self._get_power_state(context, instance)
self._instance_update(context,
instance_uuid,
power_state=current_power_state,
task_state=None)
self._notify_about_instance_usage(instance, "power_on.end")
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def rebuild_instance(self, context, instance_uuid, **kwargs):
"""Destroy and re-make this instance.
A 'rebuild' effectively purges all existing data from the system and
remakes the VM with given 'metadata' and 'personalities'.
:param context: `nova.RequestContext` object
:param instance_uuid: Instance Identifier (UUID)
:param injected_files: Files to inject
:param new_pass: password to set on rebuilt instance
"""
try:
self._rebuild_instance(context, instance_uuid, kwargs)
except exception.ImageNotFound:
msg = _("Cannot rebuild instance [%(instance_uuid)s]"
", because the given image does not exist.")
LOG.error(msg % instance_uuid, context=context)
self._set_instance_error_state(context, instance_uuid)
except Exception as exc:
msg = _("Cannot rebuild instance [%(instance_uuid)s]: %(exc)s")
LOG.error(msg % locals(), context=context)
self._set_instance_error_state(context, instance_uuid)
def _rebuild_instance(self, context, instance_uuid, kwargs):
context = context.elevated()
LOG.audit(_("Rebuilding instance %s"), instance_uuid, context=context)
instance = self.db.instance_get_by_uuid(context, instance_uuid)
self._notify_about_instance_usage(instance, "rebuild.start")
current_power_state = self._get_power_state(context, instance)
self._instance_update(context,
instance_uuid,
power_state=current_power_state,
vm_state=vm_states.REBUILDING,
task_state=None)
network_info = self._get_instance_nw_info(context, instance)
self.driver.destroy(instance, self._legacy_nw_info(network_info))
self._instance_update(context,
instance_uuid,
vm_state=vm_states.REBUILDING,
task_state=task_states.BLOCK_DEVICE_MAPPING)
instance.injected_files = kwargs.get('injected_files', [])
network_info = self.network_api.get_instance_nw_info(context,
instance)
device_info = self._setup_block_device_mapping(context, instance)
self._instance_update(context,
instance_uuid,
vm_state=vm_states.REBUILDING,
task_state=task_states.SPAWNING)
# pull in new password here since the original password isn't in the db
instance.admin_pass = kwargs.get('new_pass',
utils.generate_password(FLAGS.password_length))
image_meta = _get_image_meta(context, instance['image_ref'])
self.driver.spawn(context, instance, image_meta,
self._legacy_nw_info(network_info), device_info)
current_power_state = self._get_power_state(context, instance)
self._instance_update(context,
instance_uuid,
power_state=current_power_state,
vm_state=vm_states.ACTIVE,
task_state=None,
launched_at=utils.utcnow())
self._notify_about_instance_usage(instance, "rebuild.end",
network_info=network_info)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def reboot_instance(self, context, instance_uuid, reboot_type="SOFT"):
"""Reboot an instance on this host."""
LOG.audit(_("Rebooting instance %s"), instance_uuid, context=context)
context = context.elevated()
instance = self.db.instance_get_by_uuid(context, instance_uuid)
self._notify_about_instance_usage(instance, "reboot.start")
current_power_state = self._get_power_state(context, instance)
self._instance_update(context,
instance_uuid,
power_state=current_power_state,
vm_state=vm_states.ACTIVE)
if instance['power_state'] != power_state.RUNNING:
state = instance['power_state']
running = power_state.RUNNING
LOG.warn(_('trying to reboot a non-running '
'instance: %(instance_uuid)s (state: %(state)s '
'expected: %(running)s)') % locals(),
context=context)
network_info = self._get_instance_nw_info(context, instance)
self.driver.reboot(instance, self._legacy_nw_info(network_info),
reboot_type)
current_power_state = self._get_power_state(context, instance)
self._instance_update(context,
instance_uuid,
power_state=current_power_state,
vm_state=vm_states.ACTIVE,
task_state=None)
self._notify_about_instance_usage(instance, "reboot.end")
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@wrap_instance_fault
def snapshot_instance(self, context, instance_uuid, image_id,
image_type='snapshot', backup_type=None,
rotation=None):
"""Snapshot an instance on this host.
:param context: security context
:param instance_uuid: nova.db.sqlalchemy.models.Instance.Uuid
:param image_id: glance.db.sqlalchemy.models.Image.Id
:param image_type: snapshot | backup
:param backup_type: daily | weekly
:param rotation: int representing how many backups to keep around;
None if rotation shouldn't be used (as in the case of snapshots)
"""
context = context.elevated()
instance_ref = self.db.instance_get_by_uuid(context, instance_uuid)
current_power_state = self._get_power_state(context, instance_ref)
self._instance_update(context,
instance_ref['id'],
power_state=current_power_state,
vm_state=vm_states.ACTIVE)
LOG.audit(_('instance %s: snapshotting'), instance_uuid,
context=context)
if instance_ref['power_state'] != power_state.RUNNING:
state = instance_ref['power_state']
running = power_state.RUNNING
LOG.warn(_('trying to snapshot a non-running '
'instance: %(instance_uuid)s (state: %(state)s '
'expected: %(running)s)') % locals())
self._notify_about_instance_usage(instance_ref, "snapshot.start")
try:
self.driver.snapshot(context, instance_ref, image_id)
finally:
self._instance_update(context, instance_ref['id'], task_state=None)
if image_type == 'snapshot' and rotation:
raise exception.ImageRotationNotAllowed()
elif image_type == 'backup' and rotation:
self.rotate_backups(context, instance_uuid, backup_type, rotation)
elif image_type == 'backup':
raise exception.RotationRequiredForBackup()
self._notify_about_instance_usage(instance_ref, "snapshot.end")
@wrap_instance_fault
def rotate_backups(self, context, instance_uuid, backup_type, rotation):
"""Delete excess backups associated to an instance.
Instances are allowed a fixed number of backups (the rotation number);
this method deletes the oldest backups that exceed the rotation
threshold.
:param context: security context
:param instance_uuid: string representing uuid of instance
:param backup_type: daily | weekly
:param rotation: int representing how many backups to keep around;
None if rotation shouldn't be used (as in the case of snapshots)
"""
# NOTE(jk0): Eventually extract this out to the ImageService?
def fetch_images():
images = []
marker = None
while True:
batch = image_service.detail(context, filters=filters,
marker=marker, sort_key='created_at', sort_dir='desc')
if not batch:
break
images += batch
marker = batch[-1]['id']
return images
image_service = nova.image.get_default_image_service()
filters = {'property-image_type': 'backup',
'property-backup_type': backup_type,
'property-instance_uuid': instance_uuid}
images = fetch_images()
num_images = len(images)
LOG.debug(_("Found %(num_images)d images (rotation: %(rotation)d)")
% locals())
if num_images > rotation:
# NOTE(sirp): this deletes all backups that exceed the rotation
# limit
excess = len(images) - rotation
LOG.debug(_("Rotating out %d backups") % excess)
for i in xrange(excess):
image = images.pop()
image_id = image['id']
LOG.debug(_("Deleting image %s") % image_id)
image_service.delete(context, image_id)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def set_admin_password(self, context, instance_uuid, new_pass=None):
"""Set the root/admin password for an instance on this host.
This is generally only called by API password resets after an
image has been built.
"""
context = context.elevated()
if new_pass is None:
# Generate a random password
new_pass = utils.generate_password(FLAGS.password_length)
max_tries = 10
for i in xrange(max_tries):
instance_ref = self.db.instance_get_by_uuid(context, instance_uuid)
instance_id = instance_ref["id"]
current_power_state = self._get_power_state(context, instance_ref)
expected_state = power_state.RUNNING
if current_power_state != expected_state:
self._instance_update(context, instance_id, task_state=None)
_msg = _('Failed to set admin password. Instance %s is not'
' running') % instance_ref["uuid"]
raise exception.Invalid(_msg)
else:
try:
self.driver.set_admin_password(instance_ref, new_pass)
LOG.audit(_("Instance %s: Root password set"),
instance_ref["uuid"])
self._instance_update(context,
instance_id,
task_state=None)
break
except NotImplementedError:
# NOTE(dprince): if the driver doesn't implement
# set_admin_password we break to avoid a loop
LOG.warn(_('set_admin_password is not implemented '
'by this driver.'))
self._instance_update(context,
instance_id,
task_state=None)
break
except Exception, e:
# Catch all here because this could be anything.
LOG.exception(e)
if i == max_tries - 1:
self._set_instance_error_state(context, instance_id)
# We create a new exception here so that we won't
# potentially reveal password information to the
# API caller. The real exception is logged above
_msg = _('Error setting admin password')
raise exception.NovaException(_msg)
time.sleep(1)
continue
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def inject_file(self, context, instance_uuid, path, file_contents):
"""Write a file to the specified path in an instance on this host."""
context = context.elevated()
instance_ref = self.db.instance_get_by_uuid(context, instance_uuid)
current_power_state = self._get_power_state(context, instance_ref)
expected_state = power_state.RUNNING
if current_power_state != expected_state:
LOG.warn(_('trying to inject a file into a non-running '
'instance: %(instance_uuid)s (state: '
'%(current_power_state)s '
'expected: %(expected_state)s)') % locals())
instance_uuid = instance_ref['uuid']
msg = _('instance %(instance_uuid)s: injecting file to %(path)s')
LOG.audit(msg % locals())
self.driver.inject_file(instance_ref, path, file_contents)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def agent_update(self, context, instance_uuid, url, md5hash):
"""Update agent running on an instance on this host."""
context = context.elevated()
instance_ref = self.db.instance_get_by_uuid(context, instance_uuid)
current_power_state = self._get_power_state(context, instance_ref)
expected_state = power_state.RUNNING
if current_power_state != expected_state:
LOG.warn(_('trying to update agent on a non-running '
'instance: %(instance_uuid)s (state: '
'%(current_power_state)s '
'expected: %(expected_state)s)') % locals())
instance_uuid = instance_ref['uuid']
msg = _('instance %(instance_uuid)s: updating agent to %(url)s')
LOG.audit(msg % locals())
self.driver.agent_update(instance_ref, url, md5hash)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def rescue_instance(self, context, instance_uuid, **kwargs):
"""
Rescue an instance on this host.
:param rescue_password: password to set on rescue instance
"""
LOG.audit(_('instance %s: rescuing'), instance_uuid, context=context)
context = context.elevated()
instance_ref = self.db.instance_get_by_uuid(context, instance_uuid)
instance_ref.admin_pass = kwargs.get('rescue_password',
utils.generate_password(FLAGS.password_length))
network_info = self._get_instance_nw_info(context, instance_ref)
image_meta = _get_image_meta(context, instance_ref['image_ref'])
with self.error_out_instance_on_exception(context, instance_uuid):
self.driver.rescue(context, instance_ref,
self._legacy_nw_info(network_info), image_meta)
current_power_state = self._get_power_state(context, instance_ref)
self._instance_update(context,
instance_uuid,
vm_state=vm_states.RESCUED,
task_state=None,
power_state=current_power_state)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def unrescue_instance(self, context, instance_uuid):
"""Rescue an instance on this host."""
LOG.audit(_('instance %s: unrescuing'), instance_uuid, context=context)
context = context.elevated()
instance_ref = self.db.instance_get_by_uuid(context, instance_uuid)
network_info = self._get_instance_nw_info(context, instance_ref)
with self.error_out_instance_on_exception(context, instance_uuid):
self.driver.unrescue(instance_ref,
self._legacy_nw_info(network_info))
current_power_state = self._get_power_state(context, instance_ref)
self._instance_update(context,
instance_uuid,
vm_state=vm_states.ACTIVE,
task_state=None,
power_state=current_power_state)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def confirm_resize(self, context, instance_uuid, migration_id):
"""Destroys the source instance."""
migration_ref = self.db.migration_get(context, migration_id)
instance_ref = self.db.instance_get_by_uuid(context,
migration_ref.instance_uuid)
self._notify_about_instance_usage(instance_ref,
"resize.confirm.start")
# NOTE(tr3buchet): tear down networks on source host
self.network_api.setup_networks_on_host(context, instance_ref,
migration_ref['source_compute'], teardown=True)
network_info = self._get_instance_nw_info(context, instance_ref)
self.driver.confirm_migration(migration_ref, instance_ref,
self._legacy_nw_info(network_info))
self._notify_about_instance_usage(instance_ref, "resize.confirm.end",
network_info=network_info)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def revert_resize(self, context, instance_uuid, migration_id):
"""Destroys the new instance on the destination machine.
Reverts the model changes, and powers on the old instance on the
source machine.
"""
migration_ref = self.db.migration_get(context, migration_id)
instance_ref = self.db.instance_get_by_uuid(context,
migration_ref.instance_uuid)
# NOTE(tr3buchet): tear down networks on destination host
self.network_api.setup_networks_on_host(context, instance_ref,
teardown=True)
network_info = self._get_instance_nw_info(context, instance_ref)
self.driver.destroy(instance_ref, self._legacy_nw_info(network_info))
topic = self.db.queue_get_for(context, FLAGS.compute_topic,
migration_ref['source_compute'])
rpc.cast(context, topic,
{'method': 'finish_revert_resize',
'args': {'instance_uuid': instance_ref['uuid'],
'migration_id': migration_ref['id']},
})
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def finish_revert_resize(self, context, instance_uuid, migration_id):
"""Finishes the second half of reverting a resize.
Power back on the source instance and revert the resized attributes
in the database.
"""
migration_ref = self.db.migration_get(context, migration_id)
instance_ref = self.db.instance_get_by_uuid(context,
migration_ref.instance_uuid)
network_info = self._get_instance_nw_info(context, instance_ref)
self._notify_about_instance_usage(instance_ref, "resize.revert.start")
old_instance_type = migration_ref['old_instance_type_id']
instance_type = instance_types.get_instance_type(old_instance_type)
self.driver.finish_revert_migration(instance_ref,
self._legacy_nw_info(network_info))
# Just roll back the record. There's no need to resize down since
# the 'old' VM already has the preferred attributes
self._instance_update(context,
instance_ref['uuid'],
memory_mb=instance_type['memory_mb'],
host=migration_ref['source_compute'],
vcpus=instance_type['vcpus'],
root_gb=instance_type['root_gb'],
ephemeral_gb=instance_type['ephemeral_gb'],
instance_type_id=instance_type['id'],
vm_state=vm_states.ACTIVE,
task_state=None)
self.db.migration_update(context, migration_id,
{'status': 'reverted'})
self._notify_about_instance_usage(instance_ref, "resize.revert.end")
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def prep_resize(self, context, instance_uuid, instance_type_id, image,
**kwargs):
"""Initiates the process of moving a running instance to another host.
Possibly changes the RAM and disk size in the process.
"""
context = context.elevated()
instance_ref = self.db.instance_get_by_uuid(context, instance_uuid)
compute_utils.notify_usage_exists(instance_ref, current_period=True)
self._notify_about_instance_usage(instance_ref, "resize.prep.start")
same_host = instance_ref['host'] == FLAGS.host
if same_host and not FLAGS.allow_resize_to_same_host:
self._set_instance_error_state(context, instance_uuid)
msg = _('destination same as source!')
raise exception.MigrationError(msg)
old_instance_type_id = instance_ref['instance_type_id']
old_instance_type = instance_types.get_instance_type(
old_instance_type_id)
new_instance_type = instance_types.get_instance_type(instance_type_id)
migration_ref = self.db.migration_create(context,
{'instance_uuid': instance_ref['uuid'],
'source_compute': instance_ref['host'],
'dest_compute': FLAGS.host,
'dest_host': self.driver.get_host_ip_addr(),
'old_instance_type_id': old_instance_type['id'],
'new_instance_type_id': instance_type_id,
'status': 'pre-migrating'})
LOG.audit(_('instance %s: migrating'), instance_ref['uuid'],
context=context)
topic = self.db.queue_get_for(context, FLAGS.compute_topic,
instance_ref['host'])
rpc.cast(context, topic,
{'method': 'resize_instance',
'args': {'instance_uuid': instance_ref['uuid'],
'migration_id': migration_ref['id'],
'image': image}})
usage_info = utils.usage_from_instance(instance_ref,
new_instance_type=new_instance_type['name'],
new_instance_type_id=new_instance_type['id'])
self._notify_about_instance_usage(instance_ref, "resize.prep.end",
usage_info=usage_info)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def resize_instance(self, context, instance_uuid, migration_id, image):
"""Starts the migration of a running instance to another host."""
migration_ref = self.db.migration_get(context, migration_id)
instance_ref = self.db.instance_get_by_uuid(context,
migration_ref.instance_uuid)
instance_type_ref = self.db.instance_type_get(context,
migration_ref.new_instance_type_id)
network_info = self._get_instance_nw_info(context, instance_ref)
self.db.migration_update(context,
migration_id,
{'status': 'migrating'})
self._notify_about_instance_usage(instance_ref, "resize.start",
network_info=network_info)
try:
disk_info = self.driver.migrate_disk_and_power_off(
context, instance_ref, migration_ref['dest_host'],
instance_type_ref, self._legacy_nw_info(network_info))
except Exception, error:
with utils.save_and_reraise_exception():
msg = _('%s. Setting instance vm_state to ERROR')
LOG.error(msg % error)
self._set_instance_error_state(context, instance_uuid)
self.db.migration_update(context,
migration_id,
{'status': 'post-migrating'})
service = self.db.service_get_by_host_and_topic(
context, migration_ref['dest_compute'], FLAGS.compute_topic)
topic = self.db.queue_get_for(context,
FLAGS.compute_topic,
migration_ref['dest_compute'])
params = {'migration_id': migration_id,
'disk_info': disk_info,
'instance_uuid': instance_ref['uuid'],
'image': image}
rpc.cast(context, topic, {'method': 'finish_resize',
'args': params})
self._notify_about_instance_usage(instance_ref, "resize.end",
network_info=network_info)
def _finish_resize(self, context, instance_ref, migration_ref, disk_info,
image):
resize_instance = False
old_instance_type_id = migration_ref['old_instance_type_id']
new_instance_type_id = migration_ref['new_instance_type_id']
if old_instance_type_id != new_instance_type_id:
instance_type = instance_types.get_instance_type(
new_instance_type_id)
instance_ref = self._instance_update(
context,
instance_ref.uuid,
instance_type_id=instance_type['id'],
memory_mb=instance_type['memory_mb'],
vcpus=instance_type['vcpus'],
root_gb=instance_type['root_gb'],
ephemeral_gb=instance_type['ephemeral_gb'])
resize_instance = True
# NOTE(tr3buchet): setup networks on destination host
self.network_api.setup_networks_on_host(context, instance_ref,
migration_ref['dest_compute'])
network_info = self._get_instance_nw_info(context, instance_ref)
self._notify_about_instance_usage(instance_ref, "finish_resize.start",
network_info=network_info)
self.driver.finish_migration(context, migration_ref, instance_ref,
disk_info,
self._legacy_nw_info(network_info),
image, resize_instance)
self._instance_update(context,
instance_ref.uuid,
vm_state=vm_states.ACTIVE,
host=migration_ref['dest_compute'],
task_state=task_states.RESIZE_VERIFY)
self.db.migration_update(context, migration_ref.id,
{'status': 'finished'})
self._notify_about_instance_usage(instance_ref, "finish_resize.end",
network_info=network_info)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def finish_resize(self, context, instance_uuid, migration_id, disk_info,
image):
"""Completes the migration process.
Sets up the newly transferred disk and turns on the instance at its
new host machine.
"""
migration_ref = self.db.migration_get(context, migration_id)
instance_ref = self.db.instance_get_by_uuid(context,
migration_ref.instance_uuid)
try:
self._finish_resize(context, instance_ref, migration_ref,
disk_info, image)
except Exception, error:
with utils.save_and_reraise_exception():
msg = _('%s. Setting instance vm_state to ERROR')
LOG.error(msg % error)
self._set_instance_error_state(context, instance_ref.uuid)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def add_fixed_ip_to_instance(self, context, instance_uuid, network_id):
"""Calls network_api to add new fixed_ip to instance
then injects the new network info and resets instance networking.
"""
instance_ref = self.db.instance_get_by_uuid(context, instance_uuid)
self._notify_about_instance_usage(instance_ref, "create_ip.start")
instance_id = instance_ref['id']
self.network_api.add_fixed_ip_to_instance(context,
instance_ref,
network_id)
network_info = self.inject_network_info(context,
instance_ref['uuid'])
self.reset_network(context, instance_ref['uuid'])
self._notify_about_instance_usage(instance_ref, "create_ip.end",
network_info=network_info)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def remove_fixed_ip_from_instance(self, context, instance_uuid, address):
"""Calls network_api to remove existing fixed_ip from instance
by injecting the altered network info and resetting
instance networking.
"""
instance_ref = self.db.instance_get_by_uuid(context, instance_uuid)
self._notify_about_instance_usage(instance_ref, "delete_ip.start")
instance_id = instance_ref['id']
self.network_api.remove_fixed_ip_from_instance(context,
instance_ref,
address)
network_info = self.inject_network_info(context,
instance_ref['uuid'])
self.reset_network(context, instance_ref['uuid'])
self._notify_about_instance_usage(instance_ref, "delete_ip.end",
network_info=network_info)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def pause_instance(self, context, instance_uuid):
"""Pause an instance on this host."""
LOG.audit(_('instance %s: pausing'), instance_uuid, context=context)
context = context.elevated()
instance_ref = self.db.instance_get_by_uuid(context, instance_uuid)
self.driver.pause(instance_ref)
current_power_state = self._get_power_state(context, instance_ref)
self._instance_update(context,
instance_ref['id'],
power_state=current_power_state,
vm_state=vm_states.PAUSED,
task_state=None)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def unpause_instance(self, context, instance_uuid):
"""Unpause a paused instance on this host."""
LOG.audit(_('instance %s: unpausing'), instance_uuid, context=context)
context = context.elevated()
instance_ref = self.db.instance_get_by_uuid(context, instance_uuid)
self.driver.unpause(instance_ref)
current_power_state = self._get_power_state(context, instance_ref)
self._instance_update(context,
instance_ref['id'],
power_state=current_power_state,
vm_state=vm_states.ACTIVE,
task_state=None)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
def host_power_action(self, context, host=None, action=None):
"""Reboots, shuts down or powers up the host."""
return self.driver.host_power_action(host, action)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
def host_maintenance_mode(self, context, host, mode):
"""Start/Stop host maintenance window. On start, it triggers
guest VMs evacuation."""
return self.driver.host_maintenance_mode(host, mode)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
def set_host_enabled(self, context, host=None, enabled=None):
"""Sets the specified host's ability to accept new instances."""
return self.driver.set_host_enabled(host, enabled)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@wrap_instance_fault
def get_diagnostics(self, context, instance_uuid):
"""Retrieve diagnostics for an instance on this host."""
instance_ref = self.db.instance_get_by_uuid(context, instance_uuid)
current_power_state = self._get_power_state(context, instance_ref)
if current_power_state == power_state.RUNNING:
LOG.audit(_("instance %s: retrieving diagnostics"), instance_uuid,
context=context)
return self.driver.get_diagnostics(instance_ref)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def suspend_instance(self, context, instance_uuid):
"""Suspend the given instance."""
LOG.audit(_('instance %s: suspending'), instance_uuid, context=context)
context = context.elevated()
instance_ref = self.db.instance_get_by_uuid(context, instance_uuid)
self.driver.suspend(instance_ref)
current_power_state = self._get_power_state(context, instance_ref)
self._instance_update(context,
instance_ref['id'],
power_state=current_power_state,
vm_state=vm_states.SUSPENDED,
task_state=None)
usage_info = utils.usage_from_instance(instance_ref)
notifier.notify('compute.%s' % self.host, 'compute.instance.suspend',
notifier.INFO, usage_info)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def resume_instance(self, context, instance_uuid):
"""Resume the given suspended instance."""
LOG.audit(_('instance %s: resuming'), instance_uuid, context=context)
context = context.elevated()
instance_ref = self.db.instance_get_by_uuid(context, instance_uuid)
self.driver.resume(instance_ref)
current_power_state = self._get_power_state(context, instance_ref)
self._instance_update(context,
instance_ref['id'],
power_state=current_power_state,
vm_state=vm_states.ACTIVE,
task_state=None)
usage_info = utils.usage_from_instance(instance_ref)
notifier.notify('compute.%s' % self.host, 'compute.instance.resume',
notifier.INFO, usage_info)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@wrap_instance_fault
def lock_instance(self, context, instance_uuid):
"""Lock the given instance."""
context = context.elevated()
LOG.debug(_('instance %s: locking'), instance_uuid, context=context)
self._instance_update(context, instance_uuid, locked=True)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@wrap_instance_fault
def unlock_instance(self, context, instance_uuid):
"""Unlock the given instance."""
context = context.elevated()
LOG.debug(_('instance %s: unlocking'), instance_uuid, context=context)
self._instance_update(context, instance_uuid, locked=False)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@wrap_instance_fault
def get_lock(self, context, instance_uuid):
"""Return the boolean state of the given instance's lock."""
context = context.elevated()
LOG.debug(_('instance %s: getting locked state'), instance_uuid,
context=context)
instance_ref = self.db.instance_get_by_uuid(context, instance_uuid)
return instance_ref['locked']
@checks_instance_lock
@wrap_instance_fault
def reset_network(self, context, instance_uuid):
"""Reset networking on the given instance."""
instance = self.db.instance_get_by_uuid(context, instance_uuid)
LOG.debug(_('instance %s: reset network'), instance_uuid,
context=context)
self.driver.reset_network(instance)
@checks_instance_lock
@wrap_instance_fault
def inject_network_info(self, context, instance_uuid):
"""Inject network info for the given instance."""
LOG.debug(_('instance %s: inject network info'), instance_uuid,
context=context)
instance = self.db.instance_get_by_uuid(context, instance_uuid)
network_info = self._get_instance_nw_info(context, instance)
LOG.debug(_("network_info to inject: |%s|"), network_info)
self.driver.inject_network_info(instance,
self._legacy_nw_info(network_info))
return network_info
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@wrap_instance_fault
def get_console_output(self, context, instance_uuid, tail_length=None):
"""Send the console output for the given instance."""
context = context.elevated()
instance_ref = self.db.instance_get_by_uuid(context, instance_uuid)
LOG.audit(_("Get console output for instance %s"), instance_uuid,
context=context)
output = self.driver.get_console_output(instance_ref)
if tail_length is not None:
output = self._tail_log(output, tail_length)
return output.decode('utf-8', 'replace').encode('ascii', 'replace')
def _tail_log(self, log, length):
try:
length = int(length)
except ValueError:
length = 0
if length == 0:
return ''
else:
return '\n'.join(log.split('\n')[-int(length):])
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@wrap_instance_fault
def get_vnc_console(self, context, instance_uuid, console_type):
"""Return connection information for a vnc console."""
context = context.elevated()
LOG.debug(_("instance %s: getting vnc console"), instance_uuid)
instance_ref = self.db.instance_get_by_uuid(context, instance_uuid)
token = str(utils.gen_uuid())
if console_type == 'novnc':
# For essex, novncproxy_base_url must include the full path
# including the html file (like http://myhost/vnc_auto.html)
access_url = '%s?token=%s' % (FLAGS.novncproxy_base_url, token)
elif console_type == 'xvpvnc':
access_url = '%s?token=%s' % (FLAGS.xvpvncproxy_base_url, token)
else:
raise exception.ConsoleTypeInvalid(console_type=console_type)
# Retrieve connect info from driver, and then decorate with our
# access info token
connect_info = self.driver.get_vnc_console(instance_ref)
connect_info['token'] = token
connect_info['access_url'] = access_url
return connect_info
def _attach_volume_boot(self, context, instance, volume, mountpoint):
"""Attach a volume to an instance at boot time. So actual attach
is done by instance creation"""
instance_id = instance['id']
instance_uuid = instance['uuid']
volume_id = volume['id']
context = context.elevated()
LOG.audit(_('Booting with volume %(volume_id)s at %(mountpoint)s'),
locals(), context=context, instance=instance)
connector = self.driver.get_volume_connector(instance)
connection_info = self.volume_api.initialize_connection(context,
volume,
connector)
self.volume_api.attach(context, volume, instance_id, mountpoint)
return connection_info
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def attach_volume(self, context, instance_uuid, volume_id, mountpoint):
"""Attach a volume to an instance."""
volume = self.volume_api.get(context, volume_id)
context = context.elevated()
instance_ref = self.db.instance_get_by_uuid(context, instance_uuid)
instance_id = instance_ref['id']
msg = _("instance %(instance_uuid)s: attaching volume %(volume_id)s"
" to %(mountpoint)s")
LOG.audit(_('Attaching volume %(volume_id)s to %(mountpoint)s'),
locals(), context=context, instance=instance_ref)
try:
connector = self.driver.get_volume_connector(instance_ref)
connection_info = self.volume_api.initialize_connection(context,
volume,
connector)
except Exception: # pylint: disable=W0702
with utils.save_and_reraise_exception():
msg = _("instance %(instance_uuid)s: attach failed"
" %(mountpoint)s, removing")
LOG.exception(msg % locals(), context=context)
self.volume_api.unreserve_volume(context, volume)
try:
self.driver.attach_volume(connection_info,
instance_ref['name'],
mountpoint)
except Exception: # pylint: disable=W0702
with utils.save_and_reraise_exception():
LOG.exception(_('Attach failed %(mountpoint)s, removing'),
locals(), context=context,
instance=instance_ref)
self.volume_api.terminate_connection(context,
volume,
connector)
self.volume_api.attach(context, volume, instance_id, mountpoint)
values = {
'instance_id': instance_id,
'connection_info': utils.dumps(connection_info),
'device_name': mountpoint,
'delete_on_termination': False,
'virtual_name': None,
'snapshot_id': None,
'volume_id': volume_id,
'volume_size': None,
'no_device': None}
self.db.block_device_mapping_create(context, values)
return True
def _detach_volume(self, context, instance, bdm):
"""Do the actual driver detach using block device mapping."""
instance_name = instance['name']
instance_uuid = instance['uuid']
mp = bdm['device_name']
volume_id = bdm['volume_id']
LOG.audit(_('Detach volume %(volume_id)s from mountpoint %(mp)s'),
locals(), context=context, instance=instance)
if instance_name not in self.driver.list_instances():
LOG.warn(_('Detaching volume from unknown instance %s'),
instance_uuid, context=context)
self.driver.detach_volume(utils.loads(bdm['connection_info']),
instance_name,
mp)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
@checks_instance_lock
@wrap_instance_fault
def detach_volume(self, context, instance_uuid, volume_id):
"""Detach a volume from an instance."""
instance_ref = self.db.instance_get_by_uuid(context, instance_uuid)
instance_id = instance_ref['id']
bdm = self._get_instance_volume_bdm(context, instance_id, volume_id)
self._detach_volume(context, instance_ref, bdm)
volume = self.volume_api.get(context, volume_id)
connector = self.driver.get_volume_connector(instance_ref)
self.volume_api.terminate_connection(context, volume, connector)
self.volume_api.detach(context.elevated(), volume)
self.db.block_device_mapping_destroy_by_instance_and_volume(
context, instance_id, volume_id)
return True
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
def remove_volume_connection(self, context, instance_id, volume_id):
"""Remove a volume connection using the volume api"""
# NOTE(vish): We don't want to actually mark the volume
# detached, or delete the bdm, just remove the
# connection from this host.
try:
instance_ref = self.db.instance_get(context, instance_id)
bdm = self._get_instance_volume_bdm(context,
instance_id,
volume_id)
self._detach_volume(context, instance_ref, bdm)
volume = self.volume_api.get(context, volume_id)
connector = self.driver.get_volume_connector(instance_ref)
self.volume_api.terminate_connection(context, volume, connector)
except exception.NotFound:
pass
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
def compare_cpu(self, context, cpu_info):
"""Checks that the host cpu is compatible with a cpu given by xml.
:param context: security context
:param cpu_info: json string obtained from virConnect.getCapabilities
:returns: See driver.compare_cpu
"""
return self.driver.compare_cpu(cpu_info)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
def create_shared_storage_test_file(self, context):
"""Makes tmpfile under FLAGS.instance_path.
This method enables compute nodes to recognize that they mounts
same shared storage. (create|check|creanup)_shared_storage_test_file()
is a pair.
:param context: security context
:returns: tmpfile name(basename)
"""
dirpath = FLAGS.instances_path
fd, tmp_file = tempfile.mkstemp(dir=dirpath)
LOG.debug(_("Creating tmpfile %s to notify to other "
"compute nodes that they should mount "
"the same storage.") % tmp_file)
os.close(fd)
return os.path.basename(tmp_file)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
def check_shared_storage_test_file(self, context, filename):
"""Confirms existence of the tmpfile under FLAGS.instances_path.
Cannot confirm tmpfile return False.
:param context: security context
:param filename: confirm existence of FLAGS.instances_path/thisfile
"""
tmp_file = os.path.join(FLAGS.instances_path, filename)
if not os.path.exists(tmp_file):
return False
else:
return True
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
def cleanup_shared_storage_test_file(self, context, filename):
"""Removes existence of the tmpfile under FLAGS.instances_path.
:param context: security context
:param filename: remove existence of FLAGS.instances_path/thisfile
"""
tmp_file = os.path.join(FLAGS.instances_path, filename)
os.remove(tmp_file)
def get_instance_disk_info(self, context, instance_name):
"""Getting infomation of instance's current disk.
Implementation nova.virt.libvirt.connection.
:param context: security context
:param instance_name: instance name
"""
return self.driver.get_instance_disk_info(instance_name)
def pre_live_migration(self, context, instance_id, time=None,
block_migration=False, disk=None):
"""Preparations for live migration at dest host.
:param context: security context
:param instance_id: nova.db.sqlalchemy.models.Instance.Id
:param block_migration: if true, prepare for block migration
"""
if not time:
time = greenthread
# Getting instance info
instance_ref = self.db.instance_get(context, instance_id)
# If any volume is mounted, prepare here.
block_device_info = self._get_instance_volume_block_device_info(
context, instance_id)
if not block_device_info['block_device_mapping']:
LOG.info(_('Instance has no volume.'), instance=instance_ref)
self.driver.pre_live_migration(block_device_info)
# NOTE(tr3buchet): setup networks on destination host
self.network_api.setup_networks_on_host(context, instance_ref,
self.host)
# Bridge settings.
# Call this method prior to ensure_filtering_rules_for_instance,
# since bridge is not set up, ensure_filtering_rules_for instance
# fails.
#
# Retry operation is necessary because continuously request comes,
# concorrent request occurs to iptables, then it complains.
network_info = self._get_instance_nw_info(context, instance_ref)
# TODO(tr3buchet): figure out how on the earth this is necessary
fixed_ips = network_info.fixed_ips()
if not fixed_ips:
raise exception.FixedIpNotFoundForInstance(instance_id=instance_id)
max_retry = FLAGS.live_migration_retry_count
for cnt in range(max_retry):
try:
self.driver.plug_vifs(instance_ref,
self._legacy_nw_info(network_info))
break
except exception.ProcessExecutionError:
if cnt == max_retry - 1:
raise
else:
LOG.warn(_("plug_vifs() failed %(cnt)d."
"Retry up to %(max_retry)d for %(hostname)s.")
% locals())
time.sleep(1)
# Creating filters to hypervisors and firewalls.
# An example is that nova-instance-instance-xxx,
# which is written to libvirt.xml(Check "virsh nwfilter-list")
# This nwfilter is necessary on the destination host.
# In addition, this method is creating filtering rule
# onto destination host.
self.driver.ensure_filtering_rules_for_instance(instance_ref,
self._legacy_nw_info(network_info))
# Preparation for block migration
if block_migration:
self.driver.pre_block_migration(context,
instance_ref,
disk)
def live_migration(self, context, instance_id,
dest, block_migration=False):
"""Executing live migration.
:param context: security context
:param instance_id: nova.db.sqlalchemy.models.Instance.Id
:param dest: destination host
:param block_migration: if true, prepare for block migration
"""
# Get instance for error handling.
instance_ref = self.db.instance_get(context, instance_id)
try:
# Checking volume node is working correctly when any volumes
# are attached to instances.
if self._get_instance_volume_bdms(context, instance_id):
rpc.call(context,
FLAGS.volume_topic,
{'method': 'check_for_export',
'args': {'instance_id': instance_id}})
if block_migration:
disk = self.driver.get_instance_disk_info(instance_ref.name)
else:
disk = None
rpc.call(context,
self.db.queue_get_for(context, FLAGS.compute_topic, dest),
{'method': 'pre_live_migration',
'args': {'instance_id': instance_id,
'block_migration': block_migration,
'disk': disk}})
except Exception:
with utils.save_and_reraise_exception():
instance_uuid = instance_ref['uuid']
LOG.exception(_('Pre live migration failed at %(dest)s'),
locals(), instance=instance_ref)
self.rollback_live_migration(context, instance_ref, dest,
block_migration)
# Executing live migration
# live_migration might raises exceptions, but
# nothing must be recovered in this version.
self.driver.live_migration(context, instance_ref, dest,
self.post_live_migration,
self.rollback_live_migration,
block_migration)
def post_live_migration(self, ctxt, instance_ref,
dest, block_migration=False):
"""Post operations for live migration.
This method is called from live_migration
and mainly updating database record.
:param ctxt: security context
:param instance_id: nova.db.sqlalchemy.models.Instance.Id
:param dest: destination host
:param block_migration: if true, prepare for block migration
"""
LOG.info(_('post_live_migration() is started..'))
instance_id = instance_ref['id']
instance_uuid = instance_ref['uuid']
# Detaching volumes.
for bdm in self._get_instance_volume_bdms(ctxt, instance_id):
# NOTE(vish): We don't want to actually mark the volume
# detached, or delete the bdm, just remove the
# connection from this host.
self.remove_volume_connection(ctxt, instance_id,
bdm['volume_id'])
# Releasing vlan.
# (not necessary in current implementation?)
network_info = self._get_instance_nw_info(ctxt, instance_ref)
# Releasing security group ingress rule.
self.driver.unfilter_instance(instance_ref,
self._legacy_nw_info(network_info))
# Database updating.
# NOTE(jkoelker) This needs to be converted to network api calls
# if nova wants to support floating_ips in
# quantum/melange
try:
# Not return if floating_ip is not found, otherwise,
# instance never be accessible..
floating_ip = self.db.instance_get_floating_address(ctxt,
instance_id)
if not floating_ip:
LOG.info(_('No floating_ip found'), instance=instance_ref)
else:
floating_ip_ref = self.db.floating_ip_get_by_address(ctxt,
floating_ip)
self.db.floating_ip_update(ctxt,
floating_ip_ref['address'],
{'host': dest})
except exception.NotFound:
LOG.info(_('No floating_ip found.'), instance=instance_ref)
except Exception, e:
LOG.error(_('Live migration: Unexpected error: cannot inherit '
'floating ip.\n%(e)s'), locals(),
instance=instance_ref)
# Define domain at destination host, without doing it,
# pause/suspend/terminate do not work.
rpc.call(ctxt,
self.db.queue_get_for(ctxt, FLAGS.compute_topic, dest),
{"method": "post_live_migration_at_destination",
"args": {'instance_id': instance_ref['id'],
'block_migration': block_migration}})
# Restore volume state
for volume_ref in instance_ref['volumes']:
self.volume_api.update(ctxt, volume_ref, {'status': 'in-use'})
# No instance booting at source host, but instance dir
# must be deleted for preparing next block migration
if block_migration:
self.driver.destroy(instance_ref,
self._legacy_nw_info(network_info))
else:
# self.driver.destroy() usually performs vif unplugging
# but we must do it explicitly here when block_migration
# is false, as the network devices at the source must be
# torn down
self.driver.unplug_vifs(instance_ref,
self._legacy_nw_info(network_info))
# NOTE(tr3buchet): tear down networks on source host
self.network_api.setup_networks_on_host(ctxt, instance_ref,
self.host, teardown=True)
LOG.info(_('Migrating instance to %(dest)s finished successfully.'),
locals(), instance=instance_ref)
LOG.info(_("You may see the error \"libvirt: QEMU error: "
"Domain not found: no domain with matching name.\" "
"This error can be safely ignored."),
instance=instance_ref)
def post_live_migration_at_destination(self, context,
instance_id, block_migration=False):
"""Post operations for live migration .
:param context: security context
:param instance_id: nova.db.sqlalchemy.models.Instance.Id
:param block_migration: if true, prepare for block migration
"""
instance_ref = self.db.instance_get(context, instance_id)
LOG.info(_('Post operation of migraton started'),
instance=instance_ref)
# NOTE(tr3buchet): setup networks on destination host
# this is called a second time because
# multi_host does not create the bridge in
# plug_vifs
self.network_api.setup_networks_on_host(context, instance_ref,
self.host)
network_info = self._get_instance_nw_info(context, instance_ref)
self.driver.post_live_migration_at_destination(context, instance_ref,
self._legacy_nw_info(network_info),
block_migration)
# Restore instance state
current_power_state = self._get_power_state(context, instance_ref)
self._instance_update(context,
instance_ref['id'],
host=self.host,
power_state=current_power_state,
vm_state=vm_states.ACTIVE,
task_state=None)
# NOTE(vish): this is necessary to update dhcp
self.network_api.setup_networks_on_host(context,
instance_ref,
self.host)
def rollback_live_migration(self, context, instance_ref,
dest, block_migration):
"""Recovers Instance/volume state from migrating -> running.
:param context: security context
:param instance_id: nova.db.sqlalchemy.models.Instance.Id
:param dest:
This method is called from live migration src host.
This param specifies destination host.
:param block_migration: if true, prepare for block migration
"""
host = instance_ref['host']
self._instance_update(context,
instance_ref['id'],
host=host,
vm_state=vm_states.ACTIVE,
task_state=None)
# NOTE(tr3buchet): setup networks on source host (really it's re-setup)
self.network_api.setup_networks_on_host(context, instance_ref,
self.host)
for bdm in self._get_instance_volume_bdms(context, instance_ref['id']):
volume_id = bdm['volume_id']
volume = self.volume_api.get(context, volume_id)
self.volume_api.update(context, volume, {'status': 'in-use'})
self.volume_api.remove_from_compute(context,
volume,
instance_ref['id'],
dest)
# Block migration needs empty image at destination host
# before migration starts, so if any failure occurs,
# any empty images has to be deleted.
if block_migration:
rpc.cast(context,
self.db.queue_get_for(context, FLAGS.compute_topic, dest),
{"method": "rollback_live_migration_at_destination",
"args": {'instance_id': instance_ref['id']}})
def rollback_live_migration_at_destination(self, context, instance_id):
""" Cleaning up image directory that is created pre_live_migration.
:param context: security context
:param instance_id: nova.db.sqlalchemy.models.Instance.Id
"""
instance_ref = self.db.instance_get(context, instance_id)
network_info = self._get_instance_nw_info(context, instance_ref)
# NOTE(tr3buchet): tear down networks on destination host
self.network_api.setup_networks_on_host(context, instance_ref,
self.host, teardown=True)
# NOTE(vish): The mapping is passed in so the driver can disconnect
# from remote volumes if necessary
block_device_info = self._get_instance_volume_block_device_info(
context, instance_id)
self.driver.destroy(instance_ref, self._legacy_nw_info(network_info),
block_device_info)
@manager.periodic_task
def _heal_instance_info_cache(self, context):
"""Called periodically. On every call, try to update the
info_cache's network information for another instance by
calling to the network manager.
This is implemented by keeping a cache of uuids of instances
that live on this host. On each call, we pop one off of a
list, pull the DB record, and try the call to the network API.
If anything errors, we don't care. It's possible the instance
has been deleted, etc.
"""
heal_interval = FLAGS.heal_instance_info_cache_interval
if not heal_interval:
return
curr_time = time.time()
if self._last_info_cache_heal + heal_interval > curr_time:
return
self._last_info_cache_heal = curr_time
instance_uuids = getattr(self, '_instance_uuids_to_heal', None)
instance = None
while not instance or instance['host'] != self.host:
if instance_uuids:
try:
instance = self.db.instance_get_by_uuid(context,
instance_uuids.pop(0))
except exception.InstanceNotFound:
# Instance is gone. Try to grab another.
continue
else:
# No more in our copy of uuids. Pull from the DB.
db_instances = self.db.instance_get_all_by_host(
context, self.host)
if not db_instances:
# None.. just return.
return
instance = db_instances.pop(0)
instance_uuids = [inst['uuid'] for inst in db_instances]
self._instance_uuids_to_heal = instance_uuids
# We have an instance now and it's ours
try:
# Call to network API to get instance info.. this will
# force an update to the instance's info_cache
self.network_api.get_instance_nw_info(context, instance)
LOG.debug(_("Updated the info_cache for instance %s") %
instance['uuid'])
except Exception:
# We don't care about any failures
pass
@manager.periodic_task
def _poll_rebooting_instances(self, context):
if FLAGS.reboot_timeout > 0:
self.driver.poll_rebooting_instances(FLAGS.reboot_timeout)
@manager.periodic_task
def _poll_rescued_instances(self, context):
if FLAGS.rescue_timeout > 0:
self.driver.poll_rescued_instances(FLAGS.rescue_timeout)
@manager.periodic_task
def _poll_unconfirmed_resizes(self, context):
if FLAGS.resize_confirm_window > 0:
self.driver.poll_unconfirmed_resizes(FLAGS.resize_confirm_window)
@manager.periodic_task
def _poll_bandwidth_usage(self, context, start_time=None, stop_time=None):
if not start_time:
start_time = utils.current_audit_period()[1]
curr_time = time.time()
if curr_time - self._last_bw_usage_poll > FLAGS.bandwith_poll_interval:
self._last_bw_usage_poll = curr_time
LOG.info(_("Updating bandwidth usage cache"))
try:
bw_usage = self.driver.get_all_bw_usage(start_time, stop_time)
except NotImplementedError:
# NOTE(mdragon): Not all hypervisors have bandwidth polling
# implemented yet. If they don't it doesn't break anything,
# they just don't get the info in the usage events.
return
for usage in bw_usage:
mac = usage['mac_address']
self.db.bw_usage_update(context,
mac,
start_time,
usage['bw_in'], usage['bw_out'])
@manager.periodic_task
def _report_driver_status(self, context):
curr_time = time.time()
if curr_time - self._last_host_check > FLAGS.host_state_interval:
self._last_host_check = curr_time
LOG.info(_("Updating host status"))
# This will grab info about the host and queue it
# to be sent to the Schedulers.
self.update_service_capabilities(
self.driver.get_host_stats(refresh=True))
@manager.periodic_task(ticks_between_runs=10)
def _sync_power_states(self, context):
"""Align power states between the database and the hypervisor.
The hypervisor is authoritative for the power_state data, but we don't
want to do an expensive call to the virt driver's list_instances_detail
method. Instead, we do a less-expensive call to get the number of
virtual machines known by the hypervisor and if the number matches the
number of virtual machines known by the database, we proceed in a lazy
loop, one database record at a time, checking if the hypervisor has the
same power state as is in the database. We call eventlet.sleep(0) after
each loop to allow the periodic task eventlet to do other work.
If the instance is not found on the hypervisor, but is in the database,
then it will be set to power_state.NOSTATE.
"""
db_instances = self.db.instance_get_all_by_host(context, self.host)
num_vm_instances = self.driver.get_num_instances()
num_db_instances = len(db_instances)
if num_vm_instances != num_db_instances:
LOG.warn(_("Found %(num_db_instances)s in the database and "
"%(num_vm_instances)s on the hypervisor.") % locals())
for db_instance in db_instances:
# Allow other periodic tasks to do some work...
greenthread.sleep(0)
db_power_state = db_instance['power_state']
try:
vm_instance = self.driver.get_info(db_instance)
vm_power_state = vm_instance['state']
except exception.InstanceNotFound:
# This exception might have been caused by a race condition
# between _sync_power_states and live migrations. Two cases
# are possible as documented below. To this aim, refresh the
# DB instance state.
try:
u = self.db.instance_get_by_uuid(context,
db_instance['uuid'])
if self.host != u['host']:
# on the sending end of nova-compute _sync_power_state
# may have yielded to the greenthread performing a live
# migration; this in turn has changed the resident-host
# for the VM; However, the instance is still active, it
# is just in the process of migrating to another host.
# This implies that the compute source must relinquish
# control to the compute destination.
LOG.info(_("During the sync_power process the "
"instance %(uuid)s has moved from "
"host %(src)s to host %(dst)s") %
{'uuid': db_instance['uuid'],
'src': self.host,
'dst': u['host']})
elif (u['host'] == self.host and
u['vm_state'] == vm_states.MIGRATING):
# on the receiving end of nova-compute, it could happen
# that the DB instance already report the new resident
# but the actual VM has not showed up on the hypervisor
# yet. In this case, let's allow the loop to continue
# and run the state sync in a later round
LOG.info(_("Instance %s is in the process of "
"migrating to this host. Wait next "
"sync_power cycle before setting "
"power state to NOSTATE")
% db_instance['uuid'])
else:
LOG.warn(_("Instance found in database but not "
"known by hypervisor. Setting power "
"state to NOSTATE"), locals(),
instance=db_instance)
vm_power_state = power_state.NOSTATE
except exception.InstanceNotFound:
# no need to update vm_state for deleted instances
continue
if vm_power_state == db_power_state:
continue
if (vm_power_state in (power_state.NOSTATE,
power_state.SHUTOFF,
power_state.SHUTDOWN,
power_state.CRASHED)
and db_instance['vm_state'] == vm_states.ACTIVE):
self._instance_update(context,
db_instance["id"],
power_state=vm_power_state,
vm_state=vm_states.SHUTOFF)
else:
self._instance_update(context,
db_instance["id"],
power_state=vm_power_state)
@manager.periodic_task
def _reclaim_queued_deletes(self, context):
"""Reclaim instances that are queued for deletion."""
if FLAGS.reclaim_instance_interval <= 0:
LOG.debug(_("FLAGS.reclaim_instance_interval <= 0, skipping..."))
return
instances = self.db.instance_get_all_by_host(context, self.host)
for instance in instances:
old_enough = (not instance.deleted_at or utils.is_older_than(
instance.deleted_at,
FLAGS.reclaim_instance_interval))
soft_deleted = instance.vm_state == vm_states.SOFT_DELETE
if soft_deleted and old_enough:
instance_uuid = instance['uuid']
LOG.info(_('Reclaiming deleted instance'), instance=instance)
self._delete_instance(context, instance)
@manager.periodic_task
def update_available_resource(self, context):
"""See driver.update_available_resource()
:param context: security context
:returns: See driver.update_available_resource()
"""
self.driver.update_available_resource(context, self.host)
def add_instance_fault_from_exc(self, context, instance_uuid, fault,
exc_info=None):
"""Adds the specified fault to the database."""
code = 500
if hasattr(fault, "kwargs"):
code = fault.kwargs.get('code', 500)
details = unicode(fault)
if exc_info and code == 500:
tb = exc_info[2]
details += '\n' + ''.join(traceback.format_tb(tb))
values = {
'instance_uuid': instance_uuid,
'code': code,
'message': fault.__class__.__name__,
'details': unicode(details),
}
self.db.instance_fault_create(context, values)
@manager.periodic_task(
ticks_between_runs=FLAGS.running_deleted_instance_poll_interval)
def _cleanup_running_deleted_instances(self, context):
"""Cleanup any instances which are erroneously still running after
having been deleted.
Valid actions to take are:
1. noop - do nothing
2. log - log which instances are erroneously running
3. reap - shutdown and cleanup any erroneously running instances
The use-case for this cleanup task is: for various reasons, it may be
possible for the database to show an instance as deleted but for that
instance to still be running on a host machine (see bug
https://bugs.launchpad.net/nova/+bug/911366).
This cleanup task is a cross-hypervisor utility for finding these
zombied instances and either logging the discrepancy (likely what you
should do in production), or automatically reaping the instances (more
appropriate for dev environments).
"""
action = FLAGS.running_deleted_instance_action
if action == "noop":
return
# NOTE(sirp): admin contexts don't ordinarily return deleted records
with utils.temporary_mutation(context, read_deleted="yes"):
for instance in self._running_deleted_instances(context):
if action == "log":
name = instance['name']
LOG.warning(_("Detected instance with name label "
"'%(name)s' which is marked as "
"DELETED but still present on host."),
locals(), instance=instance)
elif action == 'reap':
name = instance['name']
LOG.info(_("Destroying instance with name label "
"'%(name)s' which is marked as "
"DELETED but still present on host."),
locals(), instance=instance)
self._shutdown_instance(context, instance, 'Terminating')
self._cleanup_volumes(context, instance['id'])
else:
raise Exception(_("Unrecognized value '%(action)s'"
" for FLAGS.running_deleted_"
"instance_action"), locals(),
instance=instance)
def _running_deleted_instances(self, context):
"""Returns a list of instances nova thinks is deleted,
but the hypervisor thinks is still running. This method
should be pushed down to the virt layer for efficiency.
"""
def deleted_instance(instance):
present = instance.name in present_name_labels
erroneously_running = instance.deleted and present
old_enough = (not instance.deleted_at or utils.is_older_than(
instance.deleted_at,
FLAGS.running_deleted_instance_timeout))
if erroneously_running and old_enough:
return True
return False
present_name_labels = set(self.driver.list_instances())
instances = self.db.instance_get_all_by_host(context, self.host)
return [i for i in instances if deleted_instance(i)]
@contextlib.contextmanager
def error_out_instance_on_exception(self, context, instance_uuid):
try:
yield
except Exception, error:
with utils.save_and_reraise_exception():
msg = _('%s. Setting instance vm_state to ERROR')
LOG.error(msg % error)
self._set_instance_error_state(context, instance_uuid)
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
def add_aggregate_host(self, context, aggregate_id, host, **kwargs):
"""Adds a host to a physical hypervisor pool."""
aggregate = self.db.aggregate_get(context, aggregate_id)
try:
self.driver.add_to_aggregate(context, aggregate, host, **kwargs)
except exception.AggregateError:
error = sys.exc_info()
self._undo_aggregate_operation(context,
self.db.aggregate_host_delete,
aggregate.id, host)
raise error[0], error[1], error[2]
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id())
def remove_aggregate_host(self, context, aggregate_id, host, **kwargs):
"""Removes a host from a physical hypervisor pool."""
aggregate = self.db.aggregate_get(context, aggregate_id)
try:
self.driver.remove_from_aggregate(context,
aggregate, host, **kwargs)
except (exception.AggregateError,
exception.InvalidAggregateAction) as e:
error = sys.exc_info()
self._undo_aggregate_operation(
context, self.db.aggregate_host_add,
aggregate.id, host,
isinstance(e, exception.AggregateError))
raise error[0], error[1], error[2]
def _undo_aggregate_operation(self, context, op, aggregate_id,
host, set_error=True):
try:
if set_error:
status = {'operational_state': aggregate_states.ERROR}
self.db.aggregate_update(context, aggregate_id, status)
op(context, aggregate_id, host)
except Exception:
LOG.exception(_('Aggregate %(aggregate_id)s: unrecoverable state '
'during operation on %(host)s') % locals())
@manager.periodic_task(
ticks_between_runs=FLAGS.image_cache_manager_interval)
def _run_image_cache_manager_pass(self, context):
"""Run a single pass of the image cache manager."""
if FLAGS.image_cache_manager_interval == 0:
return
try:
self.driver.manage_image_cache(context)
except NotImplementedError:
pass
|